WeakHashMap的并发应用

第一步:生成一个全局WeakHashMap变量

private static WeakHashMap lockMap = new WeakHashMap(50);

第二步:从MAP中取对象。如果有就取出,如果没有就新建放到MAP中


 /**
* 得到同步锁,用完丢弃即可
*
* @param key
* @return
*/
protected static Object getSynLockObject(String key) {
synchronized (lockMap) {
Object o = lockMap.get(key);
if (o == null) {
o = new Object();
lockMap.put(key, o);
}
return o;
}
}


第三步:锁住不同的对象,这样可以对同一对象进行同步。不同对象可以并发

public boolean processPaymentResult(YeepayResult result) {
long orderSeqId = result.getOrderSeqId();
// 只要这个Key不丢,同步锁就能起作用,所以要显式的引用这个key值
String synLockKey = String.valueOf(orderSeqId);
Object synLock = PayCenter.getSynLockObject(synLockKey);
/**
* 对同一个订单的操作需要进行同步,防止出错
*/
synchronized (synLock) {
return synchroProcessPaymentResult(result);
}
}



例:并发情况下,对数据进行加1操作,插入数据库
	private Map lockMap = new WeakHashMap(); //confirm every thread get lock object is the same object
private String lockPrefix = this.getClass().getName()+"incrementSequenceNum";
private int incrementSequenceNum(String sID, String tID, TopicIndexItem cacheTopic){
String syn = lockPrefix + sID+tID;
String value = lockMap.get(syn);
if(value == null){
synchronized(lockPrefix){
if(lockMap.get(syn)==null){
lockMap.put(syn, syn);
}
}
value = lockMap.get(syn);
}
//syn = syn.intern();
int sequenceNum = 0;
synchronized(value){
sequenceNum = DB.getTopicSequenceNum(sID, tID)+1;
DB.incrementTopicSequenceNum(sID, tID);
if(cacheTopic!=null){
cacheTopic.setMaxSequenceNum(sequenceNum);
}
}
return sequenceNum;
}

你可能感兴趣的:(WeakHashMap的并发应用)