码迷,mamicode.com
首页 > 其他好文 > 详细

ReentrantLock修饰类文件,实现按类获取锁的逻辑

时间:2021-03-10 13:38:38      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:nal   加锁   逻辑   ring   实现   对象   写入   oid   str   

1.ReentrantLock 给类文件加锁,实现类似synchronized(class)的功能

核心是类文件中,使用static修饰的reentrantLock对象

public class SourceCache {

    public static final Lock reentrantLock = new ReentrantLock();

    /**
     * 系统名,devopsdata的映射map
     */
    private static Map<String,DevopsData> devopsDataCache;

    /**
     * 系统名, jonedata的映射map
     */
    private static Map<String,JoneData> joneDataCache;

    public static Map<String, DevopsData> getDevopsDataCache() {
        return devopsDataCache;
    }

    public static Map<String, JoneData> getJoneDataCache() {
        return joneDataCache;
    }

    public static void setDevopsDataCache(Map<String, DevopsData> devopsDataCache) {
        reentrantLock.lock();
        try {
            SourceCache.devopsDataCache = devopsDataCache;
        }finally {
            reentrantLock.unlock();
        }
    }

    public static void setJoneDataCache(Map<String, JoneData> joneDataCache) {
        reentrantLock.lock();
        try {
            SourceCache.joneDataCache = joneDataCache;
        }finally {
            reentrantLock.unlock();
        }
    }

}

2.加锁,执行写入,解锁三部曲

reentrantLock.lock();
try {
    SourceCache.joneDataCache = joneDataCache;
}finally {
    reentrantLock.unlock();
}

ReentrantLock修饰类文件,实现按类获取锁的逻辑

标签:nal   加锁   逻辑   ring   实现   对象   写入   oid   str   

原文地址:https://www.cnblogs.com/PythonOrg/p/14509925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!