Confusion about thread safety - SimpleDateFormat example

后端 未结 7 1155
野的像风
野的像风 2021-01-02 03:57

I have a question about thread safety. From what I have been told, SimpleDateFormat is not thread safe. I was wondering what effects it would have if I use it the followin

7条回答
  •  清歌不尽
    2021-01-02 04:42

    SimpleDateFormat has instance-wide state while parsing and is therefore not thread safe. If you use it from multiple threads it will crash (well like java crashes :-), no process crash and the like). Removing static keyword doesn't necessarily cure the problem because it depends on the instance and it still might be used from several threads.

    You can create a local instance within the method above so that each parsing happens with its own formatter or play with threadlocal variables.

提交回复
热议问题