Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety - reading mutable objects (java)

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?

like image 657
Richard H Avatar asked Jan 12 '23 04:01

Richard H


2 Answers

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.

like image 113
Dariusz Avatar answered Jan 19 '23 20:01

Dariusz


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.

like image 22
Aniket Thakur Avatar answered Jan 19 '23 19:01

Aniket Thakur