一定時間しか保持しないMap
とりあえず最低限のメソッドしか実装してないけどこんな感じ??
最初、HashMap を継承して作ろうとか思ったんだけど型推論回りで挫折……
なんかカッコワルイ><
/** * */ package org.yoshiori.collection.utils; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * @author yoshiori * */ public class TimeLimitHashMap<K, V> { private final Map<K, TimeAndValue> map = new HashMap<K, TimeAndValue>(); private long timelimit = 5 * 60 * 1000; public TimeLimitHashMap() { } /** * @param timelimit */ public TimeLimitHashMap(long timelimit) { this.timelimit = timelimit; } @SuppressWarnings("unchecked") public boolean containsValue(Object value) { clean(); try { TimeAndValue timeAndValue = new TimeAndValue(new Date(), (V) value); return map.containsValue(timeAndValue); } catch (Exception e) { return false; } } public V get(Object key) { TimeAndValue timeAndValue = map.get(key); clean(); if(timeAndValue != null){ return timeAndValue.getValue(); } return null; } public V put(K key, V value) { TimeAndValue timeAndValue = new TimeAndValue(new Date(), value); map.put(key, timeAndValue); clean(); return value; } public V remove(Object key) { TimeAndValue timeAndValue = map.remove(key); clean(); if(timeAndValue != null){ return timeAndValue.getValue(); } return null; } private void clean(){ for(Entry<K,TimeAndValue> entry : map.entrySet()){ if(checkTimeout(entry.getValue().getTime())){ map.remove(entry); } } } public boolean checkTimeout(Date date){ return System.currentTimeMillis() - date.getTime() > timelimit; } /** * */ private static final long serialVersionUID = 1L; private class TimeAndValue { /** * @param time * @param value */ private TimeAndValue(Date time, V value) { this.time = time; this.value = value; } /** * @return the time */ public Date getTime() { return time; } /** * @return the value */ public V getValue() { return value; } private Date time; private V value; /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimeAndValue other = (TimeAndValue) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } }
もっと良い書きかたありそう……
教えてエロい人!!
Collections#synchronizedMap 出来るように Map インターフェース持つべきかなぁ……