Added TimedHashSet that entries have limited TTL

This commit is contained in:
Ziver Koc 2015-11-20 21:29:05 +01:00
parent 66bebc6f52
commit 33e749dfc7
2 changed files with 91 additions and 0 deletions

View file

@ -0,0 +1,52 @@
package zutil.struct;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* This is a timed HashSet. Each entry has a limited time to live.
*/
public class TimedHashSet<T> {
private HashMap<T, Long> map;
private long ttl;
/**
* @param ttl milliseconds the entries will live
*/
public TimedHashSet(long ttl){
this.ttl = ttl;
this.map = new HashMap<>();
}
/**
* @return true if the object already existed in the set which will reset the TTL.
*/
public boolean add(T o){
return map.put(o, System.currentTimeMillis()) != null;
}
public boolean contains(Object o){
if(map.containsKey(o)){
if(map.get(o) + ttl < System.currentTimeMillis()) // entry to old
map.remove(o);
else
return true;
}
return false;
}
/**
* Iterates through the Set and removes all entries that has passed the TTL
*/
public void garbageCollect(){
for(T o : map.keySet()){
if(map.get(o) + ttl < System.currentTimeMillis()) // entry to old
map.remove(o);
}
}
}

View file

@ -0,0 +1,39 @@
package zutil.test;
import org.junit.Test;
import zutil.struct.TimedHashSet;
import static org.junit.Assert.*;
/**
* Created by Ziver on 2015-11-20.
*/
public class TimedHashSetTest {
public static final String ENTRY = "key";
@Test
public void zeroTTL() throws InterruptedException {
TimedHashSet set = new TimedHashSet(0);
set.add(ENTRY);
Thread.sleep(1);
assertFalse(set.contains(ENTRY));
}
@Test
public void tenMsTTL() throws InterruptedException {
TimedHashSet set = new TimedHashSet(10);
set.add(ENTRY);
Thread.sleep(1);
assert(set.contains(ENTRY));
Thread.sleep(10);
assertFalse(set.contains(ENTRY));
}
@Test
public void oneSecTTL() throws InterruptedException {
TimedHashSet set = new TimedHashSet(1000);
set.add(ENTRY);
Thread.sleep(1);
assert(set.contains(ENTRY));
}
}