Concurrency and Hashmaps in Java

Since I have looked last (a while ago, may be java 3) there are lot of enhancements to concurrency in Java. I needed a stateful java object that gets updated once in a while but gets read a lot from multiple threads on a tomcat server. I could use the synchronized methods on that data object but that would lock the object both for reads and writes.

So I was looking to see if there are any native structures in Java that can do this more efficiently. I am of the kind that will not look if I don?t need something. Good and bad.

So this page is how that research went, looking for answers for efficient reads. I will summarize the research quickly in this introductory statement and the rest you can see in the rest of the document.

Quick Summary

There is a LOT of concurrency support in Java now!

Starting around Java 5, lot of things got added. Some of these features include at a high level

Volatile - to sync memory reads between threads

ReadWriteLock - to enhance when reads are more often than write

StampedLock - enhancement on ReadWriteLock to provide for optimistic reads

Then there are specific type of collection objects that are already coded correctly to give some of the needed behavior out of the box. These include

ConcurrentHashMap - Faster reads and writes. Yet consistent. Uses over 16 locks underneath.

CopyOnWriteArrayList - To speedup frequent reads by not locking the dataset at all

These improvements right in the base concurrency model, and are not withstanding such functional aspects of the new java such as streams, lambda functions, thread executors, futures etc. I then ran into such external efforts such as Akka (actor based programming), and Guava (Googles core java libraries).

As I have suspected, but realizing now, for concurrency and others, Java is a new animal, (probably for a while), now! It seem to have shed its skin of simplicity :)