Synchronizing non-thread-safe code

I need to do a SimpleDateFormat. My code looks like this:

println( ( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSSS" ) ).format( new Date() ) + "," + session( INDIVIDUAL_ID ).as[String] + "," + session( USER_NAME ).as[String] )

The docs for SimpleDateFormat says it is not thread safe. Since I am creating a new one every time, that probably doesn't matter, right?

But if I wanted to be more efficient, I could create the SimpleDateFormat object once, and then just reference it. But then I would need to synchronize access to the object, wouldn't I? What is the scala way of doing that?

What about using ThreeTen backport that we already ship and is threadsafe, instead of this old SimpleDateFormat crap?

Then, generally speaking, if you really have to use some non-thread-safe parser, the best practice is to use a ThreadLocal, as we use just a few threads.

I’m trying to find an example of how to do this ( and things like it ) using ThreeTen, as suggested. Specifically, I have need of getting today’s date in the format of YYYY-MM-DD, and just the year, as YYYY.

I’m not having a lot of luck. I look up ThreeTen, and all I find is how to create a date object (of various flavors). I try going to the JavaDocs, and I get a 404 error. So I can’t find any sample code for how to go from the date object to a string with a well defined format. Maybe a documentation deficiency?

Anybody have a working documentation link, or a snippet of sample code that I can use, preferably that includes the import line required to compile it? :slight_smile:

http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

Thanks!