RandomCache.java
1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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));
}
}