JavaAntiPatterns

Collection of bad coding practices

Archive for the ‘Threads’ Category

Measure time intervals using System.currentTimeMillis()

with 6 comments

Well, what’s wrong with a common practice of measuring elapsed time in the code like this:

(bad)

long startTime = System.currentTimeMillis();
// ...
long elapsedTime = System.currentTimeMillis() - startTime;

The approach is based on an intuitive assumption that the values returned by currentTimeMillis() (in general, the current system time expressed as a number of milliseconds since midnight, January 1, 1970 UTC) grow smoothly and always are greater in the future than in the past. This is not always the case.

A simple example when this assumption fails is adjusting the system clock. On the most of the modern systems, correction of the clock is performed automatically by polling a value from the NTP server in a specific period of time. If this correction happens in the middle of your operation, the measured time interval will be wrong or even negative. Note that the typical computer clocks have an error in tens or even hundreds of milliseconds per hour that means that the correction offset will be up to few seconds if it is performed once a day.

It is safer to use the System.nanoTime() method which does not depend on a system clock, so it’s guaranteed that its value grows smoothly from the past to the future:

(good)

long startTime = System.nanoTime();
// ...
long elapsedTime = (System.nanoTime() - startTime) / 1000000; // ms

And remember that the nanoTime values has nothing to do with any real absolute time, so don’t try to use it for the Date objects, for instance.

See also: Inside the Hotspot VM: Clocks, Timers and Scheduling Events

Written by Alex

March 15, 2012 at 4:13 am

Posted in Threads

Tagged with

Unneccessary thread safety of StringBuffer

leave a comment »

Use StringBuilder rather then StringBuffer, unless synchronization is required. StringBuilder is not thread safe, and therefore avoids the synchronization overhead of StringBuffer.

(submitted by Robert J. Walker)

Written by Alex

August 22, 2008 at 4:07 am

Posted in Strings, Threads

Tagged with , ,