Java 7 Calendar.getInstance, TimeZone.getTimeZone

2019-04-12 04:33发布

问题:

After upgrading my runtime to Java 7 I see incredible slowness... and my program is spending all of its time in the SimpleDateFormat constructor. As described in a great post here: http://coffeedriven.org/?p=83 the TimeZone code is now checking for the presence of an application context in the static synchronized method getDefaultInAppContext().

The problem for me is that it's Spring Batch file reader code that is creating a new SimpleDateFormat object for each line that it reads!

Anyone got a work around for this?

回答1:

SimpleDateFormat has always been slow, now I learn that it is even slower in Java 7.

Like @MK we also cache them. But note that it is not threadsafe. We ended up creating ThreadLocals.

JodaTime is highly recommended, though I have never used it and I don't know it has date formatting



回答2:

We solved this by making a change to Spring Batch itself. For now the change is in a local copy but I've entered a Jira issue and hope to contribute our fix back to Spring Batch itself.

The change itself is to change the use of SimpleDateFormat from a member variable to an injected one (which seems more Spring-like anyway). This lets us control its lifecycle.



回答3:

I'm happy to report that this was fixed in JDK-8074002 which ships in Java 9. It's now down to a #clone().



回答4:

Joda Time is the best Date Time API for date-time calculations. Remember that if your requirements need a different time zone, you should use the JodaTime API.