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