Making DateFormat Threadsafe. What to use, synchronized or Thread local

前端 未结 6 1548
甜味超标
甜味超标 2020-12-17 22:14

I want to make following code thread safe. What is the best way to achieve it?

private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance(         


        
6条回答
  •  伪装坚强ぢ
    2020-12-17 22:48

    You can

    1. Create a new DateFormat instance every time you need one.

    2. Use a synchronized block, as pointed by @Giovanni Botta.

    3. Use ThreadLocal:

      private static final ThreadLocal THREADLOCAL_FORMAT =
          new ThreadLocal() {
              @Override protected DateFormat initialValue() {
                  return DateFormat.getDateTimeInstance();
              }
          };
      
      public static final String eventTypeToDateTimeString(long timestamp) {
          return THREADLOCAL_FORMAT.get().format(new Date(timestamp));
      }
      

    Actually, using ThreadLocal might give you the best performance if you have a thread pool (meaning threads are reused), which most web containers do.

    Reference

    http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html

提交回复
热议问题