Clock Fixed For Deterministic Time
Inject java.time.Clock instead of calling Instant.now() everywhere: fixed clocks return the same instant forever and offset clocks shift the system time.
Code
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class InvoiceClock {
// 业务代码依赖注入 Clock,而不是直接调 Instant.now()
static Instant issueInvoiceAt(Clock clock) {
return Instant.now(clock);
}
public static void main(String[] args) {
Instant now = Instant.now();
Clock system = Clock.systemUTC();
// 固定时钟:任何时刻读到的都是同一瞬点,断言可复现
Clock frozen = Clock.fixed(now, ZoneId.of("UTC"));
System.out.println("fixed returns same instant: " + issueInvoiceAt(frozen).equals(now));
System.out.println("frozen reads: " + LocalDateTime.now(frozen));
// 偏移时钟:把系统时间平移一个固定量(模拟明天到期的账单)
Clock shifted = Clock.offset(system, Duration.ofHours(24));
System.out.println("system is before shifted: " + Instant.now(system).isBefore(Instant.now(shifted)));
// 固定时钟不再流动:两次读取完全相同
System.out.println("frozen twice equal: "
+ Instant.now(frozen).equals(Instant.now(frozen)));
}
}Inside the snippet
Count the class InvoiceClock and the functions issueInvoiceAt and main as the entire surface area of Clock Fixed For Deterministic Time.
Putting it to use
Signature: static Instant issueInvoiceAt(Clock clock)
Running the file prints labeled results such as fixed returns same instant:, frozen reads:, system is before shifted: — each operation’s effect is visible in the output.
There are 1 call inside main — issueInvoiceAt — executed top to bottom.
Core lines
return Instant.now(clock);
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
FAQ
- What does Clock Fixed For Deterministic Time print when run?
- Invoke the file as-is — the `fixed returns same instant:`, `frozen reads:`, `system is before shifted:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.