Confusion about thread safety - SimpleDateFormat example

后端 未结 7 1099
野的像风
野的像风 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:39

    Not sure what type of problems you would see if you did it this way. But the Javadocs warn against concurrent access to the SimpleDateFormat and the way your using it would definetly involve concurrent access. Removing the static would not eliminate the concurrency problem unless you were implementing some type of synchronization policy for the enclosing class or otherwise preventing multiple threads from accessing the class.

    You could try to create a SimpleDateFormat for each thread by instantiating it within the body of a method and ensuring that the reference to SimpleDateFormat never "escapes" the method. In other words, declare the variable, instantiate the object, and use the object within the same method. This would ensure that the reference for that SimpleDateFormat would be removed when the method exits.

提交回复
热议问题