Name: nt126004 Date: 09/21/2001
java version "1.4.0-beta2"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-beta2-b77)
Java HotSpot(TM) Client VM (build 1.4.0-beta2-b77, mixed mode)
The synchronized collection wrappers don't synchronize properly and can cause
non-deterministic behaviour when batch operations (e.g. addAll) are invoked.
The wrappers generally synchronize on the mutex before delegating the operation
to the underlying collection. The underlying collection then typically
iterates over the argument collection, performing some action for each
element. If the argument collection is a synchronized wrapper, all iteration
on it is supposed to be guarded by a synchronization block (see
Collections.synchronizedCollection); if this is not done, the documentation
warns of possible non-deterministic behaviour. However, the iteration over the
argument collection is never done under a synchronization lock, and is thus
vulnerable.
The following code will throw a ConcurrentModificationException, even though
both collections are only being accessed through the synchronized wrappers.
import java.util.*;
public class SyncTest {
public static void main(String[] args) {
final Collection c1 = Collections.synchronizedCollection(new ArrayList());
final Collection c2 = Collections.synchronizedCollection(new ArrayList());
c1.add("a"); c1.add("b");
new Thread(new Runnable() {
public void run() {
while(true) {
c1.add("c");
c1.remove("c");
}
}
}).start();
while(true) {
c2.addAll(c1);
c2.removeAll(c1);
}
}
}
(Review ID: 132344)
======================================================================