Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat adds random zeroes

I have an Android app that outputs a csv with several hundred lines per second. Each line has a timestamp that is basically generated like this:

String formatTimeStamp (Calendar cal)
{
    SimpleDateFormat timeFormatISO = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    return timeFormatISO.format(cal.getTime());
}

Some timestamps (maybe one in a thousand) have unexpected zeroes in them and look something like this:

2016-04-12T09:0011:30

2016-04-12T0009:0011:30

2016-04-0012T09:11:30

The occurrences seem completely arbitrary, at least I don't see any pattern behind them. Sometimes there are several thousand lines between two wrong lines, sometimes there is just one.

The date format is defined in only one place in the code.

Edit:

Here

are the faulty timestamps of my last run, just so you can take a look at it. The only thing I have noted about them is that it's always two leading zeroes in front of a date element, never in front of the year, though.

Edit 2:

Issue resolved! Turns out SimpleDateFormat is not thread safe and does weird things to strings if used incorrectly. I didn't know multithreading would be an issue, so I didn't point it out in the initial question. Sorry about the confusion.

like image 991
karpfen Avatar asked Mar 03 '26 06:03

karpfen


1 Answers

"Turns out SimpleDateFormat is not thread safe and does weird things to strings if used incorrectly."

The code you showed us in your Question is thread-safe unless the value of cal is being handled in a non-safe way.

The SimpleDateFormat instance is thread-confine; i.e. no other threads can see it. Therefore, its thread-safety or otherwise is not relevant.

My guess is that in your actual code you had multiple threads attempting to share a SimpleDateFormat instance. The javadoc says:

"It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."

like image 168
Stephen C Avatar answered Mar 04 '26 19:03

Stephen C