Question

I have a shared resource - a simple POJO wrapping a HashMap - that will be initialised once at startup and then only ever read, possibly simultaneously, by many threads (context is a web application). Do I need to synchronise access to the object (or alternatively use a concurrent hashap) or is safe to have multiple simultaneous reads? Will synchronizing add significant overhead?

Was it helpful?

Solution

You can skip synchronization for the read access to that map if you make sure that all writes happen-before all reads. What it means is described in JLS 7 chapter 17.4.5.

In practice, you will have to make sure that the HashMap is populated before any other threads that will access it are started and that its contents are not modified after that.

The reason this solution will work is that Thread.start() call enforces a synchronization and therefore guarantees that all changes made prior to that call will be visible to both old and new threads after that call. Should you modify the object after that call this guarantee would be lost and a synchronized access would be necessary.

OTHER TIPS

If you are sure all you will need is to perform read operations you do not need synchronization. This is also the same reason there are different locks - read and write in ReadWriteLock.

A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

As you have no writers there is no need for synchronizing.

As the results of multiple reads do not depend on the sequence of events, I would say you don't encounter race conditions (http://en.wikipedia.org/wiki/Race_condition) and it is therefore not necessary to synchronize access.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top