Test a deadline at the exact cutoff in Java
Inject a fixed clock so the result is reproducible. An exclusive deadline considers a request that arrives exactly at the cutoff late.
A simple example
Ask twice for the time
- Start with A fixed clock at noon
- Do this Ask twice for the time
- Result Noon both times
Apply it to a real problem
- Start with An arrival at 11:59:59 or noon
- Do this Compare with a strict noon deadline
- Result On time, then late
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.time.*;
public class Main {
public static void main(String[] args) throws Exception {
Instant cutoff = Instant.parse("2024-04-01T12:00:00Z");
for (Instant arrival : new Instant[]{cutoff.minusSeconds(1), cutoff}) {
Clock clock = Clock.fixed(arrival, ZoneOffset.UTC);
System.out.println(Instant.now(clock).isBefore(cutoff) ? "on time" : "late");
}
}
}
on time late