欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java多线程-模拟一个缓存代理

程序员文章站 2022-04-23 11:58:15
...

示例

package com.zhihua.subject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 缓存代理
 * @author caizh
 *
 */
public class CacheDemo {

    private Map<String, Object> cache = new HashMap<>();
    private ReadWriteLock rWriteLock = new ReentrantReadWriteLock();
    public static void main(String[] args) {


    }

    public Object getData(String key) {
        rWriteLock.readLock().lock();
        Object value = null;
        try {
            value = cache.get(key);
            if(value == null) {
                rWriteLock.readLock().unlock();
                rWriteLock.readLock().lock();
                try {
                    if(value==null) {
                        value = "aaa";// 去获取到数据,并赋值
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    rWriteLock.writeLock().unlock();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rWriteLock.readLock().unlock();
        }
        return value;
    }
}