Does Collections.unmodifiableList(list) require a lock? Does Collections.unmodifiableList(list) require a lock? multithreading multithreading

Does Collections.unmodifiableList(list) require a lock?


It doesn't need to be synchronized since the unmodifiable list is wrapping the synchronized one. But there's not much use for synchronizing on an unmodifiable list, other than for the purpose of iteration, which requires manual synchronization regardless:

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());}

Failure to follow this advice may result in non-deterministic behavior.

EDIT: As Ferrybig points out, it's actually not possible to synchronize safely with the unmodifiable wrapper. You may want to consider an alternative thread-safety solution, such as CopyOnWriteArrayList.


The only place where the synchronized should be used is when you loop over it, as explained by the javadoc:

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

However, you cannot do that once you wrapped it in a unmodifiableList, making it unsafe for a return result. It may return corrupted data in the case of concurrent access.

Instead of returning your backend list, it may be better to return a copy of the backend, so the calling doesn't need to worry about synchronized performance.

public List getProductList(){    synchronized (productList) {       return new ArrayList<>(productList);    }}