开发者

If two processes updating a Collection at a time then which exception will be raised?

If two processes in an application are updating one java.util.List objec开发者_运维技巧t then which kind of exception will be raised?


Depending on the implementation and the exact timing involved, a wide array of effects may happen:

  • you might get "lucky" and nothing bad happens (this might even be the common case).
  • you might get get a ConcurrentModificationException
  • you might not get an exception and simply lose one of the updates (or both!)
  • you might not get an exception and one of the updates might get lost in an endless loop (happened to me with a HashMap once, not very likely for simple List implementations, but could still be possible)
  • you might not get an exception and introduce wrong state in your list (for example one element inserted correctly, followed by a null element).

The problem is that reliably detecting if a problem occurred isn't much easier than preventing those problems from occurring in the first place, but is a lot less useful. So the sane approach is to use a concurrent data structure and/or synchronization, as appropriate.


That depends on the exact List implementation (there are no java.util.List objects because it is an interface). ArrayList states:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.


Processes cannot share a List. However two threads can share a list.

Some Lists support concurrent updating and don't produce an exception. Other List do not support concurrent updates and may produce an Exception, but this is not guarenteed for all operations.

In short if you want to modify the List and us it in another thread, you should use a thread safe collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜