1

If I would write a Clock application and I need to increase short seconds value literally after each second in time can I rely on Thread.sleep(1000) method?

Will it work fine if I would have millions of clocks running at the same time?

1
  • 2
    @AndriodNoob, this question is best suited for StackOverflow, not P.SE Jan 26, 2011 at 19:34

3 Answers 3

2

No, you cannot rely on Thread.sleep(1000), as it is up to the CPU scheduler as to when your thread is actually next run.

On top of that, CPU timings are not exactly accurate, so you will get natural deviation from true time unless you synchronize with a proper time service (atomic clock).

Having said that however, if you really are intending to run 'millions of clocks', you would be better served having a single timer that is being updated and merely storing the offset to that timer in each instance of the clock.

Also, by reducing the time the thread sleeps and updating the seconds only as appropriate, you can increase your accuracy. Note well though, as mentioned above, the sleep time is not guaranteed. This means even if you asked it to sleep for 10ms, it is technically possible for it not to return in 10 seconds (or, <<insert arbitrary time here>>

0

You generally want to update your seconds count at least a couple of times a second, otherwise it can be nearly an entire second out of sync with the real clock.

If at all possible, from there you want to have only one thread sleeping and updating the seconds value, and have a priority queue of events that need to be serviced. Each update, the clock looks at the event at the front of the priority queue, and if you've reached its time, processes it and checks the next one.

0

Look into the Java Concurrent API package. There are a number of new APIs that deal with multithreading and non-blocking algorithms.

For example, instead of having your program call Thread.sleep(1000), you can set up an [ScheduledExecutorService][1] and schedule a task to run every second. This will call your code and you use that to update your clock ticks. This move your code into a more producer/consumer model.

With Java 5, the need for such low-level access to thread (ie wait/notify) are alleviated. Take a look at some of the new stuff in the Java Concurrent package

[1]: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.