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.

JavaData Integrity

Code

snippet
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

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.