Tatanan
Tatanan

Reputation: 207

Java: synchronizing list

I have an ArrayList and I manipulate it ONLY within a synchronized block, should I use Collections.synchronizedList too? Example:

List list = Collections.synchronizedList(new ArrayList());    
// versus List list = new ArrayList();    
synchronized(list) {
      // my code
}

Upvotes: 3

Views: 132

Answers (3)

axtavt
axtavt

Reputation: 242786

  • If you only access your list within synchronized blocks, you don't need synchronizedList()

  • If you only access your list using elementary operations (add(), remove(), etc) and invocations of these operations don't depend on each other (i.e. atomicity is not an issue), you can use only synchronizedList() without explicit synchronized blocks

  • If you want to be able to invoke elementary operations without synchronized blocks, but also have compound operations (including iteration) that should be atomic, you need both synchronizedList() and synchornized blocks for compound operations

Upvotes: 1

CodeBlind
CodeBlind

Reputation: 4569

Using an explicit synchronized block and using Collections.synchronizedList(new ArrayList()) will work equivalently, with respect to mutual exclusion. However, if you must iterate over the list returned by the call to Collections, you must explicitly synchronize on that list externally anyway, per the java spec (sorry, SO won't let me link to it here).

Another thing to consider is overhead. Collections.synchronizedList(List orig) creates a new object that controls access to the original list implementation. Depending on how often you plan to make this call, and how many different ways you access the original list object, you may be better off synchronizing it externally.

Upvotes: 1

Amir Afghani
Amir Afghani

Reputation: 38561

Just use the synchronized declaration, no need for the explicit synchronized block:

List list = Collections.synchronizedList(new ArrayList());

The only way to change the contents of the list is by invoking add or remove, which is now decorated with synchronized versions of those methods thanks to this declaration.

Upvotes: 1

Related Questions