0
# Deadline Management
1
2
Absolute time-based deadline management with automatic cancellation and timeout conversion capabilities for time-bounded operations.
3
4
## Capabilities
5
6
### Deadline Creation
7
8
Create deadlines that represent absolute points in time, generally for tracking when a task should be completed.
9
10
```java { .api }
11
/**
12
* Create a deadline that will expire at the specified offset based on the system ticker.
13
* @param duration A non-negative duration
14
* @param units The time unit for the duration
15
* @return A new deadline
16
*/
17
public static Deadline after(long duration, TimeUnit units);
18
19
/**
20
* Create a deadline that will expire at the specified offset based on the given Ticker.
21
* @param duration A non-negative duration
22
* @param units The time unit for the duration
23
* @param ticker Where this deadline refers the current time
24
* @return A new deadline
25
*/
26
public static Deadline after(long duration, TimeUnit units, Deadline.Ticker ticker);
27
28
/**
29
* Returns the ticker that's based on system clock.
30
* @return System ticker instance
31
*/
32
public static Deadline.Ticker getSystemTicker();
33
```
34
35
**Usage Examples:**
36
37
```java
38
import java.util.concurrent.TimeUnit;
39
40
// Create a deadline 30 seconds from now
41
Deadline deadline = Deadline.after(30, TimeUnit.SECONDS);
42
43
// Create a deadline 5 minutes from now
44
Deadline longDeadline = Deadline.after(5, TimeUnit.MINUTES);
45
46
// Create deadline with custom ticker (mainly for testing)
47
Ticker customTicker = new CustomTicker();
48
Deadline testDeadline = Deadline.after(10, TimeUnit.SECONDS, customTicker);
49
```
50
51
### Context with Deadline
52
53
Create cancellable contexts that will automatically cancel when a deadline is reached.
54
55
```java { .api }
56
/**
57
* Create a new context which will cancel itself after the given duration from now.
58
* @param duration Duration until cancellation
59
* @param unit Time unit for the duration
60
* @param scheduler Executor service for scheduling the cancellation
61
* @return CancellableContext that will be cancelled at the deadline
62
*/
63
public Context.CancellableContext withDeadlineAfter(long duration, TimeUnit unit, ScheduledExecutorService scheduler);
64
65
/**
66
* Create a new context which will cancel itself at the given Deadline.
67
* @param newDeadline The deadline for automatic cancellation
68
* @param scheduler Executor service for scheduling the cancellation
69
* @return CancellableContext that will be cancelled at the deadline
70
*/
71
public Context.CancellableContext withDeadline(Deadline newDeadline, ScheduledExecutorService scheduler);
72
73
/**
74
* Get the deadline associated with this context, if any.
75
* @return A Deadline or null if no deadline is set
76
*/
77
public Deadline getDeadline();
78
```
79
80
**Usage Examples:**
81
82
```java
83
import java.util.concurrent.Executors;
84
import java.util.concurrent.ScheduledExecutorService;
85
86
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
87
88
// Create context that cancels after 5 seconds
89
Context.CancellableContext timedContext = Context.current()
90
.withDeadlineAfter(5, TimeUnit.SECONDS, scheduler);
91
92
try {
93
timedContext.run(() -> {
94
Context current = Context.current();
95
while (!current.isCancelled()) {
96
// This will automatically stop after 5 seconds
97
doWork();
98
}
99
});
100
} finally {
101
timedContext.cancel(null);
102
}
103
104
// Create context with specific deadline
105
Deadline deadline = Deadline.after(10, TimeUnit.MINUTES);
106
Context.CancellableContext deadlineContext = Context.current()
107
.withDeadline(deadline, scheduler);
108
```
109
110
### Deadline Status Checking
111
112
Check if a deadline has expired and get information about time remaining.
113
114
```java { .api }
115
/**
116
* Returns whether this deadline has expired.
117
* @return true if expired, false otherwise
118
*/
119
public boolean isExpired();
120
121
/**
122
* How much time is remaining in the specified time unit.
123
* @param unit The time unit for the returned value
124
* @return Time remaining, or negative value if already expired
125
*/
126
public long timeRemaining(TimeUnit unit);
127
```
128
129
**Usage Examples:**
130
131
```java
132
Deadline deadline = Deadline.after(30, TimeUnit.SECONDS);
133
134
// Check if deadline has passed
135
if (deadline.isExpired()) {
136
System.out.println("Deadline has already expired!");
137
return;
138
}
139
140
// Get remaining time in different units
141
long remainingSeconds = deadline.timeRemaining(TimeUnit.SECONDS);
142
long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS);
143
144
System.out.println("Time remaining: " + remainingSeconds + " seconds");
145
146
// Keep checking until expired
147
while (!deadline.isExpired()) {
148
doWork();
149
if (deadline.timeRemaining(TimeUnit.SECONDS) < 5) {
150
System.out.println("Warning: Less than 5 seconds remaining!");
151
}
152
}
153
```
154
155
### Deadline Comparison
156
157
Compare deadlines to determine which expires first. Deadlines must be created with the same Ticker.
158
159
```java { .api }
160
/**
161
* Is this deadline before another deadline.
162
* @param other Deadline to compare with (must use same Ticker)
163
* @return true if this deadline is before the other
164
*/
165
public boolean isBefore(Deadline other);
166
167
/**
168
* Return the minimum deadline of this or another deadline.
169
* @param other Deadline to compare with (must use same Ticker)
170
* @return The deadline that expires first
171
*/
172
public Deadline minimum(Deadline other);
173
174
/**
175
* Compare this deadline to another deadline.
176
* @param that Deadline to compare with (must use same Ticker)
177
* @return Negative if this is before, positive if after, zero if equal
178
*/
179
public int compareTo(Deadline that);
180
181
/**
182
* Check equality with another object. Two deadlines are equal if they have
183
* the same ticker and deadline time.
184
* @param object Object to compare with
185
* @return true if equal, false otherwise
186
*/
187
public boolean equals(Object object);
188
189
/**
190
* Get hash code for this deadline based on ticker and deadline time.
191
* @return Hash code value
192
*/
193
public int hashCode();
194
195
/**
196
* String representation showing time remaining until deadline.
197
* @return Human-readable string representation
198
*/
199
public String toString();
200
```
201
202
**Usage Examples:**
203
204
```java
205
Deadline deadline1 = Deadline.after(30, TimeUnit.SECONDS);
206
Deadline deadline2 = Deadline.after(60, TimeUnit.SECONDS);
207
208
// Check which deadline comes first
209
if (deadline1.isBefore(deadline2)) {
210
System.out.println("Deadline1 expires first");
211
}
212
213
// Get the earliest deadline
214
Deadline earliestDeadline = deadline1.minimum(deadline2);
215
216
// Sort deadlines (implements Comparable)
217
List<Deadline> deadlines = Arrays.asList(deadline2, deadline1);
218
Collections.sort(deadlines); // deadline1 will come first
219
```
220
221
### Deadline Modification
222
223
Create new deadlines offset from existing ones.
224
225
```java { .api }
226
/**
227
* Create a new deadline that is offset from this deadline.
228
* @param offset Amount to offset (positive for later, negative for earlier)
229
* @param units Time unit for the offset
230
* @return New deadline offset from this one
231
*/
232
public Deadline offset(long offset, TimeUnit units);
233
```
234
235
**Usage Example:**
236
237
```java
238
Deadline originalDeadline = Deadline.after(60, TimeUnit.SECONDS);
239
240
// Create deadline 30 seconds later
241
Deadline laterDeadline = originalDeadline.offset(30, TimeUnit.SECONDS);
242
243
// Create deadline 15 seconds earlier
244
Deadline earlierDeadline = originalDeadline.offset(-15, TimeUnit.SECONDS);
245
246
// Original deadline is unchanged
247
assert originalDeadline.timeRemaining(TimeUnit.SECONDS) == 60;
248
```
249
250
### Scheduled Execution on Deadline
251
252
Schedule tasks to run when a deadline expires.
253
254
```java { .api }
255
/**
256
* Schedule a task to be run when the deadline expires.
257
* @param task Task to run on expiration
258
* @param scheduler Executor service to schedule the task
259
* @return ScheduledFuture which can be used to cancel execution
260
*/
261
public ScheduledFuture<?> runOnExpiration(Runnable task, ScheduledExecutorService scheduler);
262
```
263
264
**Usage Example:**
265
266
```java
267
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
268
Deadline deadline = Deadline.after(30, TimeUnit.SECONDS);
269
270
// Schedule cleanup task to run when deadline expires
271
ScheduledFuture<?> cleanupTask = deadline.runOnExpiration(() -> {
272
System.out.println("Deadline expired, cleaning up resources...");
273
cleanupResources();
274
}, scheduler);
275
276
// Can cancel the scheduled task if needed
277
if (operationCompleted) {
278
cleanupTask.cancel(false);
279
}
280
```
281
282
### Custom Ticker
283
284
Create custom time sources for testing or specialized timing needs.
285
286
```java { .api }
287
/**
288
* Time source representing nanoseconds since fixed but arbitrary point in time.
289
* DO NOT use custom Ticker implementations in production.
290
*/
291
public abstract static class Ticker {
292
/**
293
* Returns the number of nanoseconds elapsed since this ticker's reference point in time.
294
* @return Nanoseconds elapsed
295
*/
296
public abstract long nanoTime();
297
}
298
```
299
300
**Usage Example (Testing Only):**
301
302
```java
303
// Custom ticker for testing - DO NOT USE IN PRODUCTION
304
public class TestTicker extends Deadline.Ticker {
305
private long currentTime = 0;
306
307
@Override
308
public long nanoTime() {
309
return currentTime;
310
}
311
312
public void advance(long nanos) {
313
currentTime += nanos;
314
}
315
}
316
317
// Use in tests only
318
TestTicker testTicker = new TestTicker();
319
Deadline testDeadline = Deadline.after(1000, TimeUnit.MILLISECONDS, testTicker);
320
321
assert !testDeadline.isExpired();
322
testTicker.advance(TimeUnit.SECONDS.toNanos(2)); // Advance 2 seconds
323
assert testDeadline.isExpired();
324
```