Friday, 18 November 2011

Java Concurrency

Java 1.4 concurrency offers java.util package,

I've come across lot of articles to find out how Hashtable and Vector is replaced by Collections.synchronized wrappers till Java 1.4. Even, the Collections.synchronized wrappers had a major drawback of fail-fast effect. While iterating the collection in a Thread (say t1) and if thread (say t2) modifies the collection, then you will end up in ConcurrentModificationException. Also, the other draw back of Collections.synchronized wrapper is that, it can be thread-safe to an extend for only simple get() and put() methods.

Java 1.5 concurrency offers java.util.concurrent package,

To get rid of fail-fast effect with Collections wrappers, one can use CopyonWriteArrayList as an replacement for Collections.synchronizedList and CopyonWriteArraySet as an replacement for Collections.synchronizedSet.

Well, the CopyonWriteArrayList locks the entire table while iteration for one Thread even the other thread cannot fetch objects from this collection.

To make it more interestingly, the Java 1.5 offers thread-safe, highly scalable collections than in 1.4.

Guys, if you have requirements like iterate over Collection and do add/remove objects into the same collection in Multithreaded environment, then ideal choice would be ConcurrentHashMap as an replacement for Hashtable/HashMap. The retrieval operations are not blocked but overlaped with update operations in ConcurrentHashMap.

Overall, I can say one should live in his own world to think twice before choosing appropriate Collection to deal while working with Multithreaded environment.

Please look into this beautiful article from the URL - https://www6.software.ibm.com/developerworks/education/j-concur/j-concur-a4.pdf

No comments:

Post a Comment