1

After this great question on how to Override Java System.currentTimeMillis, where Jon Skeet suggests to make use of a replaceable clock, I was thinking on how it could work with the Timer class.

// Clock() is replacing Date()
Date workTime = new Clock().plusSeconds(30).toDate();
Timer timer = new Timer();
timer.schedule(new ExampleClass(), workTime);

If clock's time is in the past, Timer() will use the system clock and fire the method instantaneously even though, ideally, it would wait until Clock() would give back a current time plus 30 seconds.

What's the best approach to dealing with this?

I was hopping for an answer a bit more practical than to keep overriding it all...

Community
  • 1
  • 1
Frankie
  • 24,627
  • 10
  • 79
  • 121

2 Answers2

0

I would same the same as the approach in the first question. Subclass Timer() and have all your code use it.

JOTN
  • 6,120
  • 2
  • 26
  • 31
  • that would do it, but is it the best alternative? I'm afraid to be re-inventing the wheel by starting to re-write it all... – Frankie Aug 06 '12 at 02:50
  • If you look at the Timer source, it pulls the time directly from System.currentTimeMillis(), so it's the same situation as trying to change Date(). If you switch over to the System source, currentTimeMillis() is a native call. – JOTN Aug 06 '12 at 13:16
0

"Favor composition over inheritance" to avoid overriding it all.

As the Clock wraps System.currentTimeMillis, wrap your Timer in a Scheduler and hand in a Clock as well.
The Scheduler makes the relevant checks on your Clock (i.e. is it past time already) and triggers its internal Timer if it finds the conditions satisfied.

Then, have your code use the Scheduler instead of a Timer.

For tests, you could replace that implementation with more specific behaviour, obviously, or use mocks.

As an additional benefit, you get an API that is custom made for your problem instead of the generic solution Java provides.

Urs Reupke
  • 6,791
  • 3
  • 35
  • 49