RandomCache.java 1.82 KB
package com.zhaoonline.coupen.cache;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ZhaoOnline<br/>
 * User: yangyoupeng<br/>
 * Date: 2016/12/15<br/>
 * Time: 18:13<br/>
 * Description:随机缓存
 */
public class RandomCache<K,V> {
    private ConcurrentHashMap<K,V> caches = null;
    private int capacity = 0;
    private List<K> keys=null;
    public RandomCache() {
        this(200);
    }
    public RandomCache(int capacity) {
        this.capacity=capacity;
        this.caches = new ConcurrentHashMap<K,V>(capacity);
        this.keys= Collections.synchronizedList(new ArrayList<K>(capacity));
    }

    public synchronized void put(K key,V value){
        caches.put(key, value);
        keys.add(key);
    }

    public synchronized void remove(K key){
        caches.remove(key);
        keys.remove(key);
    }

    public K randomKey(){
        Random random = new Random();
        if(keys.size() == 0){
            return null;
        }
        int keyIndex=random.nextInt(keys.size());
        K key=keys.get(keyIndex);
        return key;
    }


    public synchronized K shuffledRandomKey(){
        List<K> clonedKeys=new ArrayList<>(keys);
        Collections.shuffle(clonedKeys);
        if(clonedKeys.size() == 0){
            return null;
        }
        return  clonedKeys.get(0);
    }

    public int size(){
        return caches.size();
    }

    public boolean isEmpty(){
        return caches.isEmpty();
    }

    public List<K> allKeys(){
        return keys;
    }

    public V getCache(String key){
        if(key == null){
            return null;
        }
      return caches.get(key);
    }

    public synchronized void clear() {
        this.caches = new ConcurrentHashMap<K,V>(capacity);
        this.keys= Collections.synchronizedList(new ArrayList<K>(capacity));
    }
}