SocketM
SocketM

Reputation: 574

Thread safe code for Simpledate

can you please tell me if the following code is thread safe and how I could test it:

      private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
     Calendar cal = new GregorianCalendar();
  TimeZone timezone = cal.getTimeZone();

     AppCalendar qCal = new AppCalendar(timezone);
    qCal.setDateToday();
    qCal.setTimeNow();


    }

public static String createTempName(final TimeZone timeZone) {
    final AppCalendar calendar = new AppCalendar(timeZone);
    calendar.setDateToday();
    calendar.setTimeNow();
    synchronized (sdf) {
        return sdf.format(calendar.getTime());
    }
}

I mention that my code runs on JVM 7 and I have to use Date types provided by this context. Unfortunately not being able to use thred save LocalDate from Java 8. I am using the string returned from method createTempName as a unique key in database column. appCalendar is class that extends java.util.GregorianCalendar.

Sincerely,

Upvotes: 0

Views: 120

Answers (1)

olsli
olsli

Reputation: 871

Yes, it is thread safe. You can test it as done in "Java DateFormat is not threadsafe" what does this leads to?. If performace is an issue I would recommend changing synchronization to ThreadLocal as in Making DateFormat Threadsafe. What to use, synchronized or Thread local.

Upvotes: 1

Related Questions