0

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,

SocketM
  • 564
  • 1
  • 19
  • 34
  • 3
    your code looks broken, you mix class parameters and function calls, can you pls update your code? – JohnnyAW Dec 07 '17 at 13:28
  • In Java 7, you can use JodaTime. Otherwise, yes, your code looks alright. But if you are really using this code from multiple threads, you'll have contention on the synchronized monitor of `sdf` - better to use ThreadLocal variables. – Erwin Bolwidt Dec 07 '17 at 13:32
  • 2
    @JohnnyAW Yes he does need `synchronized` , that's the whole point of this question. Read the Javadoc of `SimpleDateFormat`: "If multiple threads access a format concurrently, it must be synchronized externally." – Erwin Bolwidt Dec 07 '17 at 13:34
  • 2
    This doesn't even compile. qCal.setXXX methods appear out of thin air with some extra } at the end. – TheJavaGuy-Ivan Milosavljević Dec 07 '17 at 13:34
  • @ErwinBolwidt ups, my bad – JohnnyAW Dec 07 '17 at 13:37

1 Answers1

1

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.

olsli
  • 831
  • 6
  • 8