1
package org.python.pydev.core.cache;
3
import java.io.Serializable;
4
import java.util.Iterator;
5
import java.util.LinkedHashMap;
7
import java.util.Map.Entry;
11
* If the cache is to be used by multiple threads,
12
* the cache must be wrapped with code to synchronize the methods
13
* cache = (Map)Collections.synchronizedMap(cache);
15
* (it is actually serializable or not depending on its keys and values)
17
public class LRUCache<Key, Val> implements Cache<Key, Val>, Serializable{
19
protected int maxSize;
21
private static final long serialVersionUID = 1L;
22
private transient int removeEntries;
23
private transient int initialMaxSize;
25
public LRUCache(int maxSize){
26
this.maxSize = maxSize;
27
cache = createMap(maxSize);
30
protected LinkedHashMap<Key, Val> createMap(int maxSize) {
31
return new LinkedHashMap<Key,Val>(maxSize+1, .75F, true) {
32
// This method is called just after a new entry has been added
33
public boolean removeEldestEntry(Map.Entry eldest) {
34
return size() > LRUCache.this.maxSize;
39
public void stopGrowAsNeeded(){
42
if(removeEntries == 0){
43
maxSize = initialMaxSize;
44
Iterator<Entry<Key, Val>> iter = cache.entrySet().iterator();
45
//go to the position of the 'eldest' entries
46
for (int i = 0; i < cache.size() - maxSize; i++) {
49
//and now remove the eldest entries
50
while(cache.size() > maxSize && iter.hasNext()){
59
* Can be used to stop removing oldest entries (this can be useful when doing some 'local' operations that want
60
* to be faster, having the new max size passed as the new 'value'. Note that other calls to this method will
61
* be ignored and will not change that limit).
63
* Also, the link between startGrowAsNeeded and stopGrowAsNeeded should be synchronized to avoid that one thread
64
* raises and another one stopping that raise (so, use this with care).
66
public void startGrowAsNeeded(int newSize){
67
if(removeEntries > 0){
68
throw new RuntimeException("There is alrdeady a new size in action. This class should be synched for this access.");
72
if(removeEntries == 1){
74
initialMaxSize = maxSize;
81
protected LinkedHashMap<Key,Val> cache;
83
public Val getObj(Key key) {
84
return cache.get(key);
87
public void remove(Key key) {
91
public void add(Key key, Val val) {