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);
    }
    }

  • 相关阅读:
    bzoj1415 NOI2005聪聪和可可
    Tyvj1952 Easy
    poj2096 Collecting Bugs
    COGS 1489玩纸牌
    COGS1487 麻球繁衍
    cf 261B.Maxim and Restaurant
    cf 223B.Two Strings
    cf 609E.Minimum spanning tree for each edge
    cf 187B.AlgoRace
    cf 760B.Frodo and pillows
  • 原文地址:https://www.cnblogs.com/panxuejun/p/7834619.html
Copyright © 2011-2022 走看看