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:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Sample2 {
public static void main(String[] args) {
new Sample2().doMain();
}
private void doMain(){
final List<String> list = Collections.synchronizedList(new ArrayList<String>());
for (int i = 0; i < 10; i++) {
list.add("value "+ i);
}
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 =new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(new Runnable(){
@Override
public void run() {
synchronized (list) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t4 = new Thread(new Runnable(){
@Override
public void run() {
for (int i=0; i <5; i++) {
list.add("New Value "+i);
System.out.println("Valued Added");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t4.start();
}
}
view raw Sample2.java hosted with ❤ by GitHub
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