Controlling time

3

I’ve been looking through the API for JSR 310 Date & Time revamp presumably slated for Java 7. There are many nice things in it, especially compared to the craptastic java.util.Date and Calendar. Throughout, the API relies on factories, immutable objects, and a host of other recommended API patterns.

But I wanted to mention one of my favorite things, which is the Clock class that acts as a facade for accessing the current time. I use “time” here somewhat loosely; in keeping with the nature of the 310 API, you can get the current point on the timeline (like System.currentTimeMillis()) or the current date, time, date/time, etc.

Anyhow, Clock is an abstract class. You actually need to get an instance of it to use it and typically you’ll use the one provided by the static method Clock.system() with something like this:

// Use pre-defined system clock
Clock clock = Clock.system();

// Create instant (nanoseconds since the epoch)
Instant now = clock.instant();

// Create human scale date (no time)
LocalDate today = clock.today();

The cool part is that Clock is intended to be subclassed so that you can control the advancement of the clock yourself, like this guy:

This is awesome for unit testing as you can create your own Clock, fix the time, control the rate at which it advances, test rolling over daylight savings time changes, time zones, etc. But all of your code just relies on Clock, which is the standard facade.

I’ll be doing a new Java 7 Preview talk in my last three No Fluff Just Stuff conferences this season if you’re interested in checking it out:

Comments

3 Responses to “Controlling time”
  1. That does seem cool.
    For my current project, we also needed something like this, so we ended up building our own Day/Instant/Clock abstraction.

  2. Ken Sipe says:

    Nice blog post… however Peter should be a good example of what could happen if you start screwing around with time :)

  3. msandoz says:

    we did this on our project to test scheduling a set of time-related requirements for a project and it worked great. we registered implementations of a time service with a factory. there was a start time and time dilation factor on our mock time service and the real one was backed by System. the only painful part was having to go to the factory but it saved us a lot of time testing scheduling that would have otherwise had to take much longer.