Why do HashTable read operations need to be locked?

59 views Asked by At

The read operation of CopyAndWriteArrayList does not need to be locked, because the write operation will copy the array and will not affect the original array, so the read operation is not locked. So what will happen if the HashTable is not locked? If it only reads the data modified by other threads, there is no problem in some business scenarios. Is this the reason why ConcurrentHashMap appeared later, the write operation is locked, the read operation is not locked, and the visibility is guaranteed through volatile, and the performance of reading and writing is improved at the same time. God please enlighten me.

1

There are 1 answers

0
Kan Robert On

HashTable is an old library. You can find that the thread synchronization scheme for old libraries in JDK is directly locked. This is a relatively simple scheme, so do it directly.

When Java became more and more popular, and the community wanted Java to have stronger performance, various thread synchronization solutions appeared after JDK5, so this is just a historical issue, and there is no need to delve into it.

You can focus more on the design ideas of new solutions, such as the ones you mentioned: CopyAndWriteArrayList and ConcurrentHashMap.