Confusion about thread safety - SimpleDateFormat example

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

    SimpleDateFormat.parse() uses an instance variable called calendar to build the date from the string. If two threads try to parse at the same time, the calendar variable will get clobbered and you'll get wrong results.

    Making the variable not static won't necessarily help, since two threads could still be using the same controller. A better solution is to either create a new DateFormat object each time you parse a date, or use thread local storage. Better still, use JodaTime which has thread safe parsers.

提交回复
热议问题