Java Synchronization: Keyword “synchronized”
What does it mean by “synchronized”?
1) Mutual ExclusiveOnly one thread can enter synchronized block.
2) Guarantee no reordering
Instruction inside synchronized block can reordered between themselves. E.g. 4, 6, 5 Instruction outside synchronized block can reorder between themselves. E.g. 2, 3 ,1.
Instruction in synchronized block cannot be reordered to mix with outside block (1, 5, 2, 3)
Instruction outside synchronized block cannot be reordered to mix with in block (7, 5, 8, 9)
3) Guarantee to get value from memory all the time, not from cache
4) Volatile variable observe next page (need validation)
After all instruction in a synchronized block get executed. All change values are pushed into memory from local cache of the thread. Also as we know data move does not work on single variable, therefore the cache line which contains the changed value got pushed to memory too.
After all instruction in a synchronized block get executed. All change values are pushed into memory from local cache of the thread. Also as we know data move does not work on single variable, therefore the cache line which contains the changed value got pushed to memory too.
Cost of the lock in "synchronized"
1) Memory Synchronization2) Mutual Exclusive, only one thread can get into "synchronized" block at one time. The other thread needs to wait3) When a thread got suspended and restart, the thread may not get the same core again. Now the thread need to load everything again to its cache. Question: Why don't we bind the thread to a specific core? Yes we can do it.4) How many times "synchronized" block slower than a normal code block? By 100+ times easily.Synchronized Exception with Hardware Optimization
In previous section we say "guarantee reordering", however the guarantee may not hold in the following case. Let say we have instruction like image above. Instruction 4, 7, 8 all required OS call for writing. It is so expensive so that at hardware level, OS decided to reorder the instruction by itself which makes the order ... 4, 7, 8, 5, 6 , 9. Again, this optimization done at OS levelIssue with Synchronization
1) No lock pooling.
If a thread does not get the lock, there is no way we can tell the thread to do something else and come back latter. It will keep spinning to wait.
If a thread does not get the lock, there is no way we can tell the thread to do something else and come back latter. It will keep spinning to wait.
2) No time lock wait
We cannot tell a thread to wait for 2s or 5s then call again. It does it on their own.
We cannot tell a thread to wait for 2s or 5s then call again. It does it on their own.
3) No interrupted lock wait : Please explain me again
4) Block structure
Synchronized block must be in the same method.
Synchronized block must be in the same method.
Comments
Post a Comment