summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/util/TimeoutHashMap.java
blob: 8655cc3ad4574d967db86c6db8dd16df3301aacf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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<K, V> implements Map<K, V>
{

	private final Map<K, TimeoutReference<V>> 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<V> 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<V>(
				false, timeout, value ) );
		return value;
	}

	@Override
	public V remove( Object key )
	{
		TimeoutReference<V> remove = map.remove( key );
		if ( remove == null )
			return null;
		return remove.get();
	}

	@Override
	public void putAll( Map<? extends K, ? extends V> m )
	{
		for ( java.util.Map.Entry<? extends K, ? extends V> entry : m.entrySet() ) {
			put( entry.getKey(), entry.getValue() );
		}
	}

	@Override
	public void clear()
	{
		map.clear();
	}

	@Override
	public Set<K> keySet()
	{
		return map.keySet();
	}
	
	public Map<K, V> getImmutableSnapshot()
	{
		Map<K, V> copy = new HashMap<>();
		for (Entry<K, TimeoutReference<V>> 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<V> values()
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public Set<java.util.Map.Entry<K, V>> entrySet()
	{
		throw new UnsupportedOperationException();
	}

}