Synchronizing on SimpleDateFormat vs. clone

2019-03-18 01:52发布

We know that the dateformat classes are not thread safe. I have a multi-threaded scenario where dateformats needs to be used. I can't really create a new instance in new thread as SimpledateFormat creation seems to be expensive(the constructor ends up calling "compile" which is costly). After some tests the only two options left for me are:

  1. External Synchronization - I really dont want to do this
  2. Cloning in each thread - Don't know whether there are some catches?

Any suggestions?

If guys have faced this before, what direction did you take.

Note: a similar question was asked before, but it was closed pointing to a apache package. I can't use new libraries for this. And I have also read this similar question on SO

7条回答
做自己的国王
2楼-- · 2019-03-18 02:27

As the similar question that you linked suggested, it really depends on your use case. If you are reusing your threads, then using a ThreadLocal value would be your best bet. If you are not reusing your threads, you have to weigh synchronization vs. object creation. If your synchronized tasks are long running (in the case where you need to parse many dates at once), your threads may end up waiting longer than it would take to create an object.

Personally, I have generally gone the route of using a ThreadLocal value, but that is because all of my use cases have been with thread reuse.

查看更多
登录 后发表回答