java 根据value进行并发同步操作

时间:2022-06-09 23:49:06
import java.util.concurrent.ConcurrentHashMap;   
import java.util.concurrent.ConcurrentMap;   
import java.util.concurrent.Semaphore;

 public abstract class ValueSynLock<T,K> {   

    /** * @Fields signMap : TODO(存储一个同步信号量,key表示同步的值) */  
    private static  ConcurrentMap<Object, Semaphore> signMap = new ConcurrentHashMap<Object, Semaphore>();   
    /** * 要执行的方法 * @throws Exception */
    public abstract K run();   
    /** * 开始执行操作 * @param value * @throws Exception */  
    public K startWork(T value) throws Exception {   
        Semaphore se = putMapAndGetSemaphore(value);   
        K ret = null;
        try {   
            se.acquire();   
            ret=run();   
            releaseLockMap(value);   
        } catch (Exception e) {
            e.printStackTrace();   
        }finally{
            se.release();   
        }
        return ret;
    }   
    /** * 释放map * @param */  
    public void releaseLockMap(T a) {   
        Semaphore se = signMap.get(a);   
        if (se != null) {   
            signMap.remove(a);   
        }   
    }   
    /** * * @param 放入同步值,获取同步信号量 * @return */  
    public Semaphore putMapAndGetSemaphore(T value) {   
        Semaphore se = signMap.get(value);   
        if (se == null) {   
            se = new Semaphore(1);   
            signMap.put(value, se);   
        }   
        return signMap.get(value);   
    }   
}