关于 ConcurrentHashMap 的同步问题

package com.seeyon.v3x.organization.domain;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

public class Test {
 
 private transient Map<String, Collection<TestCllection>> rels = new ConcurrentHashMap<String, Collection<TestCllection>>();


 /**
  * @param args
  */
 public static void main(String[] args) {
  for(int i=0;i<2000;i++){

  Map rels=new Test().rels;
  new testThread(rels).start();
  new testThread(rels).start();
  try {
   Thread.sleep(100);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  new testThread(rels).start();
  
  }


 }
 
 

}

class testThread extends Thread{
 Map<String, Collection<TestCllection>> rels=null;
 testThread(Map<String, Collection<TestCllection>> m){
  this.rels=m;
  
 }
 public void run(){
  String type="Test";
  Collection<TestCllection> typeRels;
//②同步一个object  
//  Object o =new Object();
//  synchronized(o)
//  {
  
//③ 同步 内存对象  
//  synchronized("T")
//  {
   typeRels= this.rels.get(type);
  if(typeRels==null){
//① 原
//   synchronized(rels)
//   {
    if(!rels.containsKey(type))
    {
     typeRels = new CopyOnWriteArraySet<TestCllection>();
     rels.put(type, typeRels);
     
     try {
      Thread.sleep(100);
     } catch (InterruptedException e) {
      System.out.println(e);
     }
    }
   }
//  }
  if(typeRels==null)
   System.out.println(this.getName());
 }
}

 

通过以上三点,和阅读ConcurrentHashMap源码,可见当去掉同步关键字synchronized或者①和②时,都得不到预想的结果,只有当③时才能使System.out不输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值