Please see the following code:
List list = Collections.synchronizedList(new ArrayList());
// ...
synchronized (list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
I know caller should synchronize when iterating a synchronied list, but I cannot understand why using “list” as lock. Inner SynchronizedList class, the private member mutex is the lock. so if caller using “list” as lock, locks are different between caller and inner. I think this truth makes synchronization no sense.
You can see the code of Collections.synchronizedList. Then you will find the implementation of synchronizedList uses the “this” to lock when add or remove method. Here you lock “list” to prevent from invoking the “add” or “remove” methods.