1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain. Use, modify, and |
4 |
* redistribute this code in any way without acknowledgement. |
5 |
*/ |
6 |
|
7 |
|
8 |
package java.util.concurrent; |
9 |
import java.util.*; |
10 |
import java.util.concurrent.atomic.*; |
11 |
|
12 |
/** |
13 |
* A DelayEntry associates a delay with an object. |
14 |
* Most typically, the object will be a runnable action. |
15 |
*/ |
16 |
|
17 |
public class DelayEntry<E> implements Comparable { |
18 |
/** |
19 |
* Sequence number to break ties, and in turn to guarantee |
20 |
* FIFO order among tied entries. |
21 |
*/ |
22 |
private static final AtomicLong sequencer = new AtomicLong(0); |
23 |
|
24 |
private final long sequenceNumber; |
25 |
private final long triggerTime; |
26 |
private final E item; |
27 |
|
28 |
/** |
29 |
* Creates a new DelayEntry for the given object with given delay. |
30 |
*/ |
31 |
DelayEntry(E x, long delay, TimeUnit unit) { |
32 |
item = x; |
33 |
triggerTime = TimeUnit.nanoTime() + unit.toNanos(delay); |
34 |
sequenceNumber = sequencer.getAndIncrement(); |
35 |
} |
36 |
|
37 |
/** |
38 |
* Equivalent to: |
39 |
* <tt> DelayEntry(x, date.getTime() - System.currentTimeMillis(), |
40 |
* TimeUnit.MiLLISECONDS)</tt> |
41 |
*/ |
42 |
DelayEntry(E x, Date date) { |
43 |
this(x, date.getTime() - System.currentTimeMillis(), |
44 |
TimeUnit.MILLISECONDS); |
45 |
} |
46 |
|
47 |
/** |
48 |
* Get the delay, in the given time unit. |
49 |
*/ |
50 |
public long getDelay(TimeUnit unit) { |
51 |
long d = triggerTime - TimeUnit.nanoTime(); |
52 |
if (d <= 0) |
53 |
return 0; |
54 |
else |
55 |
return unit.convert(d, TimeUnit.NANOSECONDS); |
56 |
} |
57 |
|
58 |
/** |
59 |
* Get the object. |
60 |
*/ |
61 |
public E get() { |
62 |
return item; |
63 |
} |
64 |
|
65 |
public int compareTo(Object other) { |
66 |
DelayEntry x = (DelayEntry)other; |
67 |
long diff = triggerTime - x.triggerTime; |
68 |
if (diff < 0) |
69 |
return -1; |
70 |
else if (diff > 0) |
71 |
return 1; |
72 |
else if (sequenceNumber < x.sequenceNumber) |
73 |
return -1; |
74 |
else |
75 |
return 1; |
76 |
} |
77 |
|
78 |
} |