Skip to main content
Code Review

Return to Answer

replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link

In your reset method, use System.nanoTime() (not System.currentTimeMillis not System.currentTimeMillis) to calculate when the time is up, such as:

this.targetTime = System.nanoTime() + seconds * 1_000_000_000;

Then calculate in getSecondsLeft, by using System.nanoTime() again, how many seconds remain until the target nanosecond value has been reached.

  • Avoid using java.util.Timer. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use a ScheduledExecutorService.
  • When changing to a ScheduledExecutorService, don't cancel or shutdown your ScheduledExecutorService, instead cancel the FutureTask that you will get when scheduling a task.
  • Don't decrease a counter once a second. Nothing guarantees that it will be called with exactly 1000 ms periodicity.

In your reset method, use System.nanoTime() (not System.currentTimeMillis) to calculate when the time is up, such as:

this.targetTime = System.nanoTime() + seconds * 1_000_000_000;

Then calculate in getSecondsLeft, by using System.nanoTime() again, how many seconds remain until the target nanosecond value has been reached.

  • Avoid using java.util.Timer. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use a ScheduledExecutorService.
  • When changing to a ScheduledExecutorService, don't cancel or shutdown your ScheduledExecutorService, instead cancel the FutureTask that you will get when scheduling a task.
  • Don't decrease a counter once a second. Nothing guarantees that it will be called with exactly 1000 ms periodicity.

In your reset method, use System.nanoTime() (not System.currentTimeMillis) to calculate when the time is up, such as:

this.targetTime = System.nanoTime() + seconds * 1_000_000_000;

Then calculate in getSecondsLeft, by using System.nanoTime() again, how many seconds remain until the target nanosecond value has been reached.

Source Link
Simon Forsberg
  • 59.7k
  • 9
  • 157
  • 311
  • Avoid using java.util.Timer. See Checking if a Java Timer is cancelled and java.util.Timer: Is it deprecated? Instead use a ScheduledExecutorService.
  • When changing to a ScheduledExecutorService, don't cancel or shutdown your ScheduledExecutorService, instead cancel the FutureTask that you will get when scheduling a task.
  • Don't decrease a counter once a second. Nothing guarantees that it will be called with exactly 1000 ms periodicity.

In your reset method, use System.nanoTime() (not System.currentTimeMillis) to calculate when the time is up, such as:

this.targetTime = System.nanoTime() + seconds * 1_000_000_000;

Then calculate in getSecondsLeft, by using System.nanoTime() again, how many seconds remain until the target nanosecond value has been reached.

lang-java

AltStyle によって変換されたページ (->オリジナル) /