blob: e86c6c74e1af28175e8315d86d043d053178d87e (
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
|
package org.openslx.util;
/**
* A reference holder that will only return the object it is holding if
* the given timeout has not been reached.
* The timeout will start anew if you set this reference to hold a new object,
* or if you retrieve the object, and refreshOnGet is set to true.
*/
public class TimeoutReference<T>
{
private final long timeoutMs;
private long deadline;
private boolean refreshOnGet;
private T item;
public TimeoutReference( boolean refreshOnGet, long timeoutMs, T item )
{
this.refreshOnGet = refreshOnGet;
this.item = item;
this.timeoutMs = timeoutMs;
this.deadline = System.currentTimeMillis() + timeoutMs;
}
public TimeoutReference( long timeoutMs, T item )
{
this( false, timeoutMs, item );
}
public synchronized T get()
{
if ( item != null ) {
final long now = System.currentTimeMillis();
if ( deadline < now ) {
item = null;
} else if ( refreshOnGet ) {
deadline = now + timeoutMs;
}
}
return item;
}
public synchronized void set( T newItem )
{
this.item = newItem;
this.deadline = System.currentTimeMillis() + timeoutMs;
}
@Override
public int hashCode()
{
return item.hashCode();
}
@Override
public boolean equals( Object o )
{
return this == o || item.equals( o );
}
}
|