Internal working of ConcurrentHashMap?

I was looking at source code of ConcurrentHashMap how how concurrent update has been handled. But looks like its to complex to understand. Then i thought if i need to implement it my self how should i go about it. I came up with simple algorithm. My question is is my algo on right path(i think yes) and if i compare it with the jre 6 prescribed implementation where it lacks at high level?

Basically we have to do locking at individual bucket level(instead of whole HashMap) so that concurrent update requires locks only for entries which got to same bucket. Now bucket gets determined based on key's hashcode.similarly if we get the lock based on hashcode, problem will be solved. So two keys having different hashcode will go to the separate buckets and hence we can use synchronize block on interned hashcode value(purpose of using interned value is so that lock is acquired on same object which lies under same bucket). In this case synchronization will happen on different interned hashcode strings. so, concurrent hashcode can happen.

So two keys having equal hashcode will go to the same buckets .So, we can use synchronize block on interned hashcode value and avoid concurrent update

here is my proposed put method

     public V put(K key, V value) {

     int hashCode = geKeyHashcode();
     String stringHashcode = hashCode + "";

     synchronized (str.intern()) { // line A

     // proceed for put operation
     }

     }

Now at line A, we can stop concurrent updates lying under same bucket/segment, though proceed for lying under separate bucket/segment

I am sure it can be improved a lot but main point it can be achieved be simple algorithm also. Is n't it?

UPDATE :- If someone can forward/point to the resource which explains java 6 prescribed ConcurrentHashMap in easier manner it would be great(I tried Googling but couldn't spot which explains how put method is implementated like usage of unsafe etc)

链接地址: http://www.djcxy.com/p/91894.html

上一篇: JDK8:取回javadoc的JDK7外观

下一篇: ConcurrentHashMap的内部工作?