77. Implementing a chess clock

Starting with JDK 8, the java.time package has an abstract class named Clock. The main purpose of this class is to allow us to plug in different clocks when needed (for example, for testing purposes). By default, Java comes with four implementations: SystemClock, OffsetClock, TickClock, and FixedClock. For each of these implementations, there are static methods in the Clock class. For example, the following code creates FixedClock (a clock that always returns the same Instant):

Clock fixedClock = Clock.fixed(Instant.now(), ZoneOffset.UTC);

There is also TickClock, which returns the current Instant ticking in whole seconds for the given time zone:

Clock tickClock = Clock.tickSeconds(ZoneId.of("Europe/Bucharest")); ...

Get Java Coding Problems now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.