Java ThreadLocal for SimpleDateFormat example

java threadlocal simpledateformat exampleThreadLocal is a class that appeared in Java 1.2 and provides thread-local variables. Each of these are accessed via get and set methods. When a thread accesses such variable it gets an independent copy.

Why do we need such functionality?

ThreadLocal use cases

ThreadLocal class is used in such cases:

  • API Simplicity
  • Syntactic sugar
  • Non-thread-safe resources caching
  • Lock striping

In our example we will discover the case for caching of the non thread safe resources like SimpleDateFormat.

ThreadLocal SimpleDateFormat example

public class CustomDateAdapter extends XmlAdapter<String, Date> {
    public final static String DATE_EXPRESSION = "\\d{4}-\\d{2}-\\d{2}";
    public final static String DATE_FORMAT = "yyyy-MM-dd";
    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public Date unmarshal(String dateStr) throws ParseException {
        if (!dateStr.matches(DATE_EXPRESSION)) {
            throw new ParseException("Invalid date format: " + dateStr, 0);
        }
        return getFormat().parse(dateStr);
    }

    @Override
    public String marshal(Date date) {
        return getFormat().format(date);
    }

    private static SimpleDateFormat getFormat() {
        SimpleDateFormat simpleDateFormat = DATE_FORMAT_THREAD_LOCAL.get();
        if (simpleDateFormat == null) {
            DATE_FORMAT_THREAD_LOCAL.set(new SimpleDateFormat(DATE_FORMAT));
        }
        return DATE_FORMAT_THREAD_LOCAL.get();
    }
}

Here you can see a ThreadLocal instance called DATE_FORMAT_THREAD_LOCAL. In the constructor we set it a new instance of SimpleDateFormat. Then in the simply need to call get() method on a ThreadLocal object to access a thread-local copy of SimpleDateFormat.

 

Leave a Reply

Be the First to Comment!