Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate ConcurrentModificationException in own class?

I have been reading "Effective Java" Item 60, which is "Favor the use of standard exceptions".

Another general-purpose exception worth knowing about is ConcurrentModificationException. This exception should be thrown if an object that was designed for use by a single thread or with external synchronization detects that it is being concurrently modified.

Normally people face with CME when they try remove from a collection while looping.

But in here I am interested about what would be a concise example on detecting a concurrent modification on self-implemented class object?

I expect it to be something like synchronizing on internal object and related boolean flag, if another thread confronts the flag being false, then throwing exception.

For a simple research I have found in source of ArrayList:

 final void checkForComodification() {
     if (modCount != expectedModCount)
         throw new ConcurrentModificationException();
 }

but the principle behind how modCount is maintained. I cannot find where it is being decremented.

like image 379
Nikolay Kuznetsov Avatar asked May 18 '26 10:05

Nikolay Kuznetsov


1 Answers

The modification count is essentially the "revision number" of the collection's state. It is incremented every time there is a structural change to the collection. It is never decremented.

When starting iteration, the iterator remembers the value of the mod count. It then periodically checks that the container's current mod count still equals the remembered value. If it doesn't -- meaning there has been a structural change since iteration began -- a ConcurrentModificationException is thrown.

like image 196
NPE Avatar answered May 19 '26 23:05

NPE