search

Home  >  Q&A  >  body text

java - ConcurrentHashMap的get为什么可以不加锁?

ringa_leeringa_lee2802 days ago831

reply all(5)I'll reply

  • 阿神

    阿神2017-04-18 10:08:21

    1. The internal implementation uses locks, so you don’t need to add another layer of locks when you use it

          『他都是复制出一个新的数组进行复制, 而非在原地操作』 你在哪里看到有复制的代码?

      2/3. If you read when the writing is not completed, you will read null. At this time, the lock is locked by the writing operation. Wait for the writing operation to unlock, and then read again.

    reply
    0
  • 阿神

    阿神2017-04-18 10:08:21

    1. get No need to lock, just reading will not change the data

    2. readValueUnderLock Normal circumstances will not be executed

    3. e.value 不会为 null 作者Doug LeaExplanation as follows

    Not quite. You are right that it should never be called. However, the JLS/JMM can be read as not absolutely forbidding it from being called because of weaknesses in required ordering relationships among finals vs volatiles set in constructors (key is final, value is volatile), wrt the reads by threads using the entry objects. (In JMM-ese, ordering constraints for finals fall outside of the synchronizes-with relation.) That's the issue the doc comment (pasted below) refers to. No one has ever thought of any practical loophole that a processor/compiler might find to produce a null value read, and it may be provable that none exist (and perhaps someday a JLS/JMM revision will fill in gaps to clarify this), but Bill Pugh once suggested we put this in anyway just for the sake of being conservatively pedantically correct. In retrospect, I'm not so sure this was a good idea, since it leads people to come up with exotic theories.

    In the higher version of jdkConncurrentHashMap has been completely rewritten, and this part of the code is gone.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:08:21

    ConncurrentHashMap was introduced by jdk5. Its operation ensures thread safety, so no locking is required

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:08:21

    Classic reading and writing model, generally no locking is required for reading

    reply
    0
  • PHPz

    PHPz2017-04-18 10:08:21

    The Get operation does not cause changes to the underlying array or linked list. The author's question may be that another thread puts at the same time during Get, or another thread removes at the same time during Get. In fact, there is no problem here. If get is in front and put is in the back, then you will get null. If remove is in front after get, you will also get null. There will be no situation where you get null if you put it first, or get obj if you remove it first. Because the final operation of remove or put is atomic setting segment[i].table[j]. The get operation has no chance to mess with this operation

    reply
    0
  • Cancelreply