package org.openslx.util; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; public class TimeoutHashMap implements Map { private final Map> map; private final long timeout; public TimeoutHashMap( long timeout ) { this.map = new HashMap<>(); this.timeout = timeout; } @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean containsKey( Object key ) { return map.containsKey( key ); } @Override public boolean containsValue( Object value ) { return map.containsValue( value ); } @Override public V get( Object key ) { TimeoutReference timeoutReference = map.get( key ); if ( timeoutReference == null ) return null; V obj = timeoutReference.get(); if ( obj == null && timeoutReference.isInvalid() ) { map.remove( key ); } return obj; } @Override public V put( K key, V value ) { map.put( key, new TimeoutReference( false, timeout, value ) ); return value; } @Override public V remove( Object key ) { TimeoutReference remove = map.remove( key ); if ( remove == null ) return null; return remove.get(); } @Override public void putAll( Map m ) { for ( java.util.Map.Entry entry : m.entrySet() ) { put( entry.getKey(), entry.getValue() ); } } @Override public void clear() { map.clear(); } @Override public Set keySet() { return map.keySet(); } public Map getImmutableSnapshot() { Map copy = new HashMap<>(); for (Entry> i : map.entrySet()) { V v = i.getValue().get(); if (i.getValue().isInvalid()) continue; copy.put(i.getKey(), v); } return Collections.unmodifiableMap( copy ); } @Override public Collection values() { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { throw new UnsupportedOperationException(); } }