Java – hashtable: why do get methods synchronize?
I know that hashtable is synchronous, but why is its get () method synchronous?
Is it just a reading method?
Solution
If the read is not synchronized, you can modify the hashtable during the read New elements can be added, the underlying array may become too small and may be replaced by larger elements, and so on If there is no sequential execution, it is difficult to deal with these situations
However, even if get does not crash when another thread modifies the hashtable, the synchronized keyword has another important aspect, cache synchronization Let's use a simplified example:
class Flag { bool value; bool get() { return value; } // WARNING: not synchronized synchronized void set(bool value) { this->value = value; } }
Set is synchronous, but get is not What happens if two threads a and b read and write this class at the same time?
1. A calls read 2. B calls set 3. A calls read
In step 3, is it ensured that a sees the modification of thread B?
No, it's not, because a can run on a different core, which uses a separate cache, where the old value still exists Therefore, we must force B to pass memory to other cores and force a to obtain new data
How do we execute it? Each time, the thread enters and leaves the synchronization block and executes the implicit memory barrier The memory barrier forces the cache to be updated However, both writers and readers are required to execute memory barrier Otherwise, the message is not conveyed correctly
In our example, thread B already uses the synchronized method set, so it passes its data modification at the end of the method However, a did not see the modified data The solution is to synchronize get, so it is forced to get updated data