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

  • 相关阅读:
    108.Convert Sorted Array to Binary Search Tree
    111.Minimum Depth of Binary Tree
    118.Pascal's Triangle
    122.Best Time to Buy and Sell Stock II
    35.搜索插入位置
    OSI参考模型
    虚拟机访问tomcat
    linux输入ifconfig找不到IP的解决办法
    分层协议、协议、接口、服务
    Spring Boot项目的创建
  • 原文地址:https://www.cnblogs.com/panxuejun/p/7834619.html
Copyright © 2011-2022 走看看