分享

Iteration that may Throw ArrayIndexOutOfBoundsException.

 moonboat 2011-05-13
Iteration that may Throw ArrayIndexOutOfBoundsException.

for (int i = 0; i < vector.size(); i++)
            doSomething(vector.get(i));
            

Even though the iteration in Listing 5.3 can throw an exception, this doesn't mean Vector isn't thread-safe. The state of the Vector is still valid and the exception is in fact in conformance with its specification. However, that something as mundane as fetching the last element or iteration throw an exception is clearly undesirable.

The problem of unreliable iteration can again be addressed by client-side locking, at some additional cost to scalability. By holding the Vector lock for the duration of iteration, as shown in Listing 5.4, we prevent other threads from modifying the Vector while we are iterating it. Unfortunately, we also prevent other threads from accessing it at all during this time, impairing concurrency.

Listing 5.4. Iteration with Client-side Locking.

synchronized (vector) {
            for (int i = 0; i < vector.size(); i++)
            doSomething(vector.get(i));
            }
            



Iterating a List with an Iterator.


List<Widget> widgetList
            = Collections.synchronizedList(new ArrayList<Widget>());
            ...
            // May throw ConcurrentModificationException
            for (Widget w : widgetList)
            doSomething(w);
            



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多