JAVA 단일 맵 캐 시

4710 단어 Java
package com.xxx.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
/**
 *         
 * 
 */
public  final class SimpleCache {
    private static final int MAX_CAPACITY = 1000;//     
    private static final Hashtable map = new Hashtable<>();

    private static SimpleCache cache = null;

    private SimpleCache(){};
    /**
     *       
     */
    public synchronized static SimpleCache getSimpleCache(){
        if(cache==null){
            cache = new SimpleCache();
        }
        return cache;
    }
    /**
     *        key
     * @param key    
     * @return  true   false
     */
    public boolean contains(String key) {

         return map.contains(key);
    }
    /**
     *     key
     * @param key    
     */
    public void remove(String key) {

        map.remove(key);
    }
    /**
     *     
     */
    public void rmoveAll (){
        map.clear();
    }
    /**
     *             val
     * @param key
     *           
     * @return
     *         key   Object 
     */
    public Object get (String key){
        return map.get(key);
    }
    /**
     *       
     * @return Map  
     */
    public Map getAll() {
        Map hashMap = new HashMap<>();
        Enumeration keys = map.keys();
        while(keys.hasMoreElements()) {
            String key = keys.nextElement();
            Object val = map.get(key);
            hashMap.put(key, val);
        }
        return hashMap;
    }
    /**
     *  key   val       
     * @param key
     *            
     * @param val
     *                Object  
     */
    public void put (String key,Object val){
        if (val == null) {
            throw new NullPointerException();
        }
        if(map.size()>= MAX_CAPACITY){
            map.clear();
            map.put(key, val);
        }
        if(map.containsKey(key)){
            return ;
        }
        map.put(key, val);
    }
}

좋은 웹페이지 즐겨찾기