liveBook · Manning

Current time

As explained in 100 Java Mistakes and How to Avoid Them

Current time is the temporal value representing the present moment as obtained from a clock, optionally including its date and time zone.

Current time is an external value that can change while a computation runs, including when a machine is suspended or execution crosses midnight. section 9.11

A flaky backup-folder test

A backup-folder method and its test each call LocalDateTime.now(). Usually both calls produce the same hour and minute, but a minute boundary can make the expected name differ from the actual folder name, causing a sporadic test failure. section 9.11

Treat clock-derived values as unstable inputs:

  • Do not assume that a value read from the external world will remain unchanged during later computation. section 9.11
  • Recognize that seemingly rare timing differences can become observable at boundaries such as a new minute or day. section 9.11
@Test
public void testBackupFolder() throws IOException {
  Path tempDir = Files.createTempDirectory("test");
  Path backupFolder = createBackupFolder(tempDir);     #1
  var nameFormat = DateTimeFormatter.ofPattern(
    "'Backup'-yyyy-MM-dd-HH-mm");
  String expectedName = nameFormat.format(LocalDateTime.now());
  assertEquals(backupFolder.getFileName().toString(),
    expectedName);
}

Shows the test pattern that reads the current time separately from backup-folder creation. section 9.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains temporal instability through a flaky-test scenario and suspension or boundary timing, without developing clock-control techniques.
Examples
Uses backup-folder names formatted from hours and minutes and a test that queries LocalDateTime.now() again.
What you can do after
Diagnose flaky tests caused by comparing results derived from separate current-time queries.
How it connects
Connects current time to LocalDateTime, date formatting, external state, and flaky tests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.