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 ...
Comments
Post a Comment