WeakHashMap的并发应用
第一步:生成一个全局WeakHashMap变量
private static WeakHashMap<String, Object> lockMap = new WeakHashMap<String, Object>(50);
/** * 得到同步锁,用完丢弃即可 * * @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); } }
private Map<String, String> lockMap = new WeakHashMap<String,String>(); //confirm every thread get lock object is the same objectprivate 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;}