Java Synchronization: The Reader

Which methods need synchronized?


Consider the following class stub. At this point there is no doubt we need to give "synchronized" to add() and remove(). How about get()? get() just does a read. Does it need a lock? 


Method like get() needs synchronized too


1) Avoid inconsistent data
get() should not look inside structure while some other threads are making multiple operator change because it could be inconsistent.

2) To get latest data from memory, not local cache
The following image describing cache system of a multi-core processor. 














As you can see each core has its own cache. The only shared memory between cores are RAM (memory). 
Let say the original value if 1|2|3. 
Processor 0 Core 0 running thread 1. Reading.
Processor 1 Core 1 running thread 2. Writing.
Thread 2 makes change to value to make it 1|2|3|4. Since add() is synchronized, the new value got added in P1C1 cache level 1, push to cache level 2, then RAM.
Thread 1 is reading. By default it looks at P0C0 cache L1 first. The value is there so it doesn't look for anywhere else. However it is the old value. It doesn't fetch the new change.

To force reader to read from Memory, we needs to make that method synchronized. The end.

Comments

Popular posts from this blog

JVM Garbage Collection (GC)