Shirgill Farhan Ansari Shirgill Farhan Ansari - 2 months ago 21
Java Question

Synchronizing a synchronized List

If I have something like this snippet-

public List<E> list = Collections.synchronizedList(new ArrayList<E>());


then if I do some operations inside a method -

boolean absent = !list.contains(x); // Statement 1
if(absent) // Statement 2
list.add(x); // Statement 3


do I need to wrap the above statements inside
synchronized(list){ ... }
to make the operations
atomic
?

Answer

do I need to wrap the above statements inside synchronized(list){ ... } to make the operations atomic?

Yes otherwise your List could be modified elsewhere in your code within the time window you call contains and add which could cause race condition issues.

It makes me thing then what is the use of Collections.synchronizedList?

Collections.synchronizedList makes your List thread safe such that you can modify it concurrently but still all method calls are executed atomically. In the case above you call contains and add that you have to execute atomically because otherwise if elsewhere we call add the result of contains could be out dated which would lead to a race condition issue. The only way to prevent race condition issues is to use a synchronize block on the same object monitor which is list in your case.