Thread security - reading mutable objects (java)

I have a common resource - a simple HashMap POJO package - that will be initialized once at startup, and then only ever read, possibly simultaneously, by many threads (the context is a web application). Do I need to synchronize access to an object (or, alternatively, use a simultaneous hash) or is it safe to have several simultaneous reads? Will synchronization add significant overhead?

+4
source share
3 answers

You can skip the synchronization for read access to this card, if you make sure that all the records happen - before everything reads. What this means is described in JLS 7, chapter 17.4.5 .

In practice, you need to make sure that the value is HashMapfilled before any other threads that access it are launched, and that after that its contents will not be changed.

The reason this solution will work is because the call Thread.start()provides synchronization and therefore ensures that all changes made before this call are visible to both old and new threads after this call. If you change the object after this call, this guarantee will be lost and synchronized access is required.

+6

, , . , - ReadWriteLock.

ReadWriteLock , . , . .

, .

+2

Source: https://habr.com/ru/post/1527289/


All Articles