关于 ConcurrentHashMap 的同步问题

本文通过一个具体的并发编程案例,探讨了如何正确使用Java的ConcurrentHashMap类来实现线程安全的数据操作。文章展示了不同同步策略的效果,并指出仅当采用特定同步方式时才能避免并发错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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不输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值