3 Replies Latest reply: Oct 7, 2008 1:01 AM by masijade RSS

    SimpleDateFormat thread safety issue

    631403
      I have a servlet that instantiates an object of a class for every request in post method, which makes that variable local to that method. This class has "private final DateFormat DOB_FORMAT = new SimpleDateFormat("MM/dd/yyyy");" and a method that calls DOB_FORMAT.parse().

      Even though the instance that has DOB_FORMAT is local we frequently see NumberFormatException on valid dates. So I am wondering if there is a bug/functionality that I am not aware of such that DOB_FORMAT is being shared accross requests. Could somebody advise?
        • 1. Re: SimpleDateFormat thread safety issue
          masijade
          Even if it were/is being shared, it wouldn't make a difference. That method act only on the input and is thread safe (unless, maybe, in some other thread you were modifying timezones and the like in the middle of a parse, but as long as all you're doing is parse and format, you needn't worry).

          Edit: How are you determining that the date string that throws that exception is valid?
          • 2. Re: SimpleDateFormat thread safety issue
            DrClap
            From the API documentation for SimpleDateFormat:

            "Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."
            • 3. Re: SimpleDateFormat thread safety issue
              masijade
              DrClap wrote:
              From the API documentation for SimpleDateFormat:

              "Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."
              Okay, I stand corrected, however, I still think that as long as you are not changing timezones, patterns, etc, that it is safe. I could easily be wrong, though.

              Edit: @OP It might help to see the code in question.