Why do I need a method in ConcurrentHashMap?

I have a question about ConcurrentHashMap in java. It internally calls readValueUnderLock. Why do I need a lock in case of operation. And in this case, this condition will be true (Entry.value == NULL) that cause readValueUnderLock to read)

+4
source share
2 answers

From java doc comment readValueUnderLock source code

  /** * Reads value field of an entry under lock. Called if value * field ever appears to be null. This is possible only if a * compiler happens to reorder a HashEntry initialization with * its table assignment, which is legal under memory model * but is not known to ever occur. */ 

From this link

Not really. You are right that it should never be called. However, JLS / JMM can be read as not allowing it to be called due to weaknesses in the required order relations between the finals vs volatiles set in the constructors (the key is final, the value is volatile) by reading through streams using input objects. (In JMM-ese, order restrictions for finals go beyond synchronization with a relationship.) This refers to the issue that is mentioned in the commentary to the document (see below). No one has ever thought about any practical loophole, the processor / compiler can find a value of zero to read, and it can be proved that no one is there (and maybe someday the JLS / JMM revision will fill in the blanks to clarify this), but Bill Pugh once suggested that we are all the same in order to be conservatively pedantically correct. In retrospect, I'm not sure if that was a good idea, as it makes people come up with exotic theories.

+4
source

To read a value from a hash map, the code must first find the value. If another thread adds a value and the first thread finds a value, it can frustrate the search. Essentially, a hash map could do something like:

 calculate hash go to location hash in the array look to see if there a list iterate through the list until value is found 

If this list is called a list of arrays, and another thread needs to resize it, this will be a big problem for a thread passing through it.

0
source

Source: https://habr.com/ru/post/1437941/


All Articles