Tuesday, December 18, 2012

Java Collections - Synchronization Myth

Introduction:

Java community tried to reduce developers pain by adding synchronization mechanism for various java collections. There are 6 flavors of API available which could help developers to synchronize different java collections. Here is the list of API:
  • Collections.synchronizedList()
  • Collections.synchronizedCollection()
  • Collections.synchronizedMap()
  • Collections.synchronizedSet()
  • Collections.synchronizedSortedMap()
  • Collections.synchronizedSortedSet()
The collections returned by these methods are capable to handle synchronization for basic operations on collections e.g. get(), set(), add(), remove() etc.

The Myth:

As soon as  developers synchronize their objects using synchronization APIs, they start to believe that they need to put more code to deal with synchronization for these objects, which is not true for all cases. Let me demonstrate this with simple example.

"An ArrayList Need to be accessed by two different threads, One thread need to iterate over list and other will try to add few new entries"

Here is threads detail:
  • t1 : This thread uses Iterator to traverse through the list
  • t2 : This thread uses for loop with index based approach
  • t3 : This thread uses Iterator with sync block to traverse through the list
  • t4 : This thread will try to add new entries in the list.
Source Code:
I tried to execute code in different combinations:

case1:

Use t1 and t4. Start both threads. 
"ConcurrentModificationException" will be thrown.

 

case2:

Use t2 and t4. Start both threads. 
Successful execution with concurrently updating the list.

 

case3:

User t3 and t4. Start both threads. 
Successful execution with no concurrent update.

Conclusion:  

Developers need to be careful about synchronization even if collections has been synchronized using Collections API.

No comments:

Post a Comment