车辆年检年审时间规定:Iteration that may Throw ArrayIndexOutOfBoundsException.

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 23:16:08
for (int i = 0; i < vector.size(); i++) doSomething(vector.get(i));
Even though theiteration inListing 5.3 can throw anexception, this doesn't mean Vector isn't thread-safe. The state of theVector is still valid and the exception is in fact in conformance withits specification. However, that something as mundane as fetching the lastelement or iteration throw an exception is clearly undesirable.
The problem of unreliable iteration can again be addressed byclient-side locking, at some additional cost to scalability. By holding theVector lock for the duration of iteration, as shown inListing 5.4, we prevent other threads from modifying theVector while we are iterating it. Unfortunately, we also prevent otherthreads from accessing it at all during this time, impairing concurrency.
Listing 5.4. Iteration withClient-side Locking.
synchronized (vector) { for (int i = 0; i < vector.size(); i++) doSomething(vector.get(i)); }
Iterating a List with an Iterator.
List widgetList = Collections.synchronizedList(new ArrayList()); ... // May throw ConcurrentModificationException for (Widget w : widgetList) doSomething(w);