search

Home  >  Q&A  >  body text

并发 - java中ConcurrentHashMap不能被加锁来执行独占访问??

我在看《java并发编程实践》,书中72页提到:由于ConcurrentHashMap不能被加锁来执行独占访问,因此我们无法使用客户端加锁来创建新的原子操作。


中英文内容如上。
请问这句话怎么理解??我看过ConcurrenHashMap源码,也知道分段锁。但是这句话似乎不太对,无论是看中文还是看英文。然后我做了如下测试(测试这个就属于客户端加锁),JDK1.6:

java
public class TestThread extends Thread { private static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>(); public void run(){ synchronized (map) { for(int i=0; i<10; i++) System.out.println("i:"+i+", thread:"+Thread.currentThread().getName()); } } public static void main(String[] args) { TestThread t = new TestThread(); Thread t1 = new Thread(t,"A"); Thread t2 = new Thread(t,"B"); t1.start(); t2.start(); } }

结果如下:

i:0, thread:A
i:1, thread:A
i:2, thread:A
i:3, thread:A
i:4, thread:A
i:5, thread:A
i:6, thread:A
i:7, thread:A
i:8, thread:A
i:9, thread:A
i:0, thread:B
i:1, thread:B
i:2, thread:B
i:3, thread:B
i:4, thread:B
i:5, thread:B
i:6, thread:B
i:7, thread:B
i:8, thread:B
i:9, thread:B

是我测试程序不对??
网上也搜了一些,有很多对这句话提出质疑的,但似乎没有人回答特别靠谱的。

==============更新分割线============
我重新整理了一下问题:我理解的ConcurrentHashMap,从内部实现来讲,是不支持独占访问的。但是通过客户端加锁的方式,是可以保证原子操作性的,但是这种选择可能不是最好的。
书中“由于ConcurrentHashMap不能被加锁来执行独占访问,因此我们无法使用客户端加锁来创建新的原子操作”这句话,从描述上和逻辑上都是有问题的,我觉得。描述上,前半句感觉完全不对;逻辑上,由于-因此这个逻辑并不成立。

PHP中文网PHP中文网2813 days ago1052

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 13:05:53

    The program you tested just uses map as an ordinary object lock. The meaning of the book is that it is not possible to lock the map and then attempt to perform a series of operations on the map to achieve the effect of atomic operations.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:05:53

    It must be the same lock

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:05:53

    Since ConcurrentHashMap cannot be locked to perform exclusive access, we cannot use client-side locking to create new atomic operations, such as adding atomic operations "if not added" to Vector in Section 4.4.1.

    I was really confused when I first understood this sentence. Finally, I turned the book back to the "4.4.1" example, and I understood it after reading it.

    Client locking and external locking must be the same lock.

    //内部加锁机制为分段锁,锁不在map实例上
    private static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
    //外部加锁是在map 实例上的
    sychronized (concurrentHashMap) {
        //
    }

    The ConcurrentHashMap synchronization mechanism has an internal segment lock, and the external lock is not the same lock as it.

    Therefore, when accessed by multiple threads, the atomicity of a thread performing a composite operation of "add if not added" on the map cannot be guaranteed, because another thread may perform an "add" operation on the map.

    My personal understanding of the above is that if I have misunderstood something wrong, I welcome your guidance.

    reply
    0
  • Cancelreply