Collections.synchronizedList and synchronized

Solution 1:

You don't need to synchronize as you put in your example. HOWEVER, very important, you need to synchronize around the list when you iterate it (as noted in the Javadoc):

It is imperative that the user manually synchronize on the returned list when iterating over it:

List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());   
}

Solution 2:

It depends on the exact contents of the synchronized block:

  1. If the block performs a single, atomic operation on the list (as in your example), the synchronized is superfluous.

  2. If the block performs multiple operations on the list -- and needs to maintain the lock for the duration of the compound operation -- then the synchronized is not superfluous. One common example of this is iterating over the list.

Solution 3:

The underlying code for Collections.synchronizedList add method is:

public void add(int index, E element) {
    synchronized (mutex) {list.add(index, element);}
}

So in your example it is not needed to add synchronisation.

Solution 4:

Also Important to note that any methods that use Iterators for example Collections.sort() will also need to be encapsulated inside a synchronized block.