From 33e749dfc7346826a9a29c06dce1c8fdfc4e7e34 Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Fri, 20 Nov 2015 21:29:05 +0100 Subject: [PATCH] Added TimedHashSet that entries have limited TTL --- src/zutil/struct/TimedHashSet.java | 52 +++++++++++++++++++++++++++ test/zutil/test/TimedHashSetTest.java | 39 ++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100755 src/zutil/struct/TimedHashSet.java create mode 100755 test/zutil/test/TimedHashSetTest.java diff --git a/src/zutil/struct/TimedHashSet.java b/src/zutil/struct/TimedHashSet.java new file mode 100755 index 00000000..e40a0ccb --- /dev/null +++ b/src/zutil/struct/TimedHashSet.java @@ -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 { + + private HashMap 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); + } + } +} diff --git a/test/zutil/test/TimedHashSetTest.java b/test/zutil/test/TimedHashSetTest.java new file mode 100755 index 00000000..87d9917d --- /dev/null +++ b/test/zutil/test/TimedHashSetTest.java @@ -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)); + } +} \ No newline at end of file