zoukankan      html  css  js  c++  java
  • 用hashmap实现自己的缓存

    @SuppressWarnings({"unchecked", "rawtypes"})
    public class DefaultCache implements Cache {
    private Map cache = new HashMap();

    private DefaultCache() {
    }

    public static DefaultCache getInstance() {
    return DefaultCacheFactory.getInstance();
    }

    private static class DefaultCacheFactory{
    private static DefaultCache instance = new DefaultCache();

    private static DefaultCache getInstance(){
    return instance;
    }
    }

    public void init() {
    cache = new HashMap();
    }

    public void stop() {
    }

    public void add(String key, Object value) {
    cache.put(key, value);
    }

    public void add(String fqn, String key, Object value) {
    Map map = (Map) cache.get(fqn);
    if (map == null) {
    synchronized (this) {
    map = (Map) cache.get(fqn);
    if(map == null){
    map = new HashMap();
    map.put(key, value); // 防止指令重排序
    cache.put(fqn, map);
    }
    }
    }
    map.put(key, value);
    }

    public Object get(String fqn, String key) {
    Map map = (Map) cache.get(fqn);
    if (map == null) {
    return null;
    }
    return map.get(key);
    }

    public Object get(String key) {
    return cache.get(key);
    }

    public Collection getValues(String key) {
    Map map = (Map) cache.get(key);
    if (map == null) {
    return new ArrayList();
    }
    return map.values();
    }

    public void remove(String fqn, String key) {
    Map map = (Map) cache.get(fqn);
    if (map != null) {
    map.remove(key);
    }
    }

    public void remove(String key) {
    cache.remove(key);
    }
    }

  • 相关阅读:
    Dockerfile
    走进Docker
    liunx 设置定时任务
    《程序员自我修养》读书笔记
    Ubuntu换源
    liunx安装python2.7.12
    预习非数值数据的编码方式
    预习原码补码
    第三章预习
    预习非数值数据的编码方式
  • 原文地址:https://www.cnblogs.com/panxuejun/p/7834619.html
Copyright © 2011-2022 走看看