Time dependent bugs

I just about pulled my hair out over the weekend on a bug that was time dependent. The code roughly looked like:

final int index = (int)(System.currentTimeMillis() / intervalPerFrame) %
numberOfFrames;
final Frame frame = frames[index];

This is perfectly legimate code and ran just fine a few months ago but was now throwing ArrayIndexOutOfBoundsException since the index was getting set to -2.

So how could a series of positive values return a negative number? Well, it just so happens that on Saturday, January 10th at 7:37:04AM 2004 the time in milliseconds goes from 1073741823999L to 1073741824000L which just so happens to correspond to 2147483647 and -2147483648 respectively when cast to an integer.

Lesson learned: be much more careful casting long to int when dealing with times. Also, when your test manager says that he’s going to perform “date testing” don’t balk since Y2K’s already over. There are a lot more issues in dealing with time than just two digit dates.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s