Thursday, January 17, 2019

Java Concurrency - SimpleDateFormat Is Not Simple

Greeting!

Formatting, parsing dates is a painful task. It always give us errors :(.
A common way to format, parse dates in Java is using SimpleDateFormat. Here is a common class we can use.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateUtils {

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private DateUtils() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.format(target);
    }

}


Do you think this is working. Let's test it.


    private static void testSimpleDateFormatInSingleThread() {
        final String source = "2019-01-11";
        System.out.println(DateUtils.parse(source));
    }

    // Fri Jan 11 00:00:00 IST 2019


Yes, it worked. Let's try it with more threads.


    private static void testSimpleDateFormatWithThreads() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        final String source = "2019-01-11";

        System.out.println(":: parsing date string ::");
        IntStream.rangeClosed(0, 20)
                .forEach((i) -> executorService.submit(() -> System.out.println(DateUtils.parse(source))));

        executorService.shutdown();
    }


Here is the result I got.


:: parsing date string ::

... omitted

Fri Jan 11 00:00:00 IST 2019
Sat Jul 11 00:00:00 IST 2111
Fri Jan 11 00:00:00 IST 2019
... omitted


Interesting result isn't? This is a common mistake most of us have done when formatting dates in Java. Why? because we are not aware of thread safety. Here is what Java doc says about 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."

When we use instance variables we should always check whether it is a thread safe class or not.

Solution 1 - ThreadLocal

We can solve this by using a ThreadLocal variable. (more about ThreadLocal)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateUtilsThreadLocal {

    public static final ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    private DateUtilsThreadLocal() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.get().parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.get().format(target);
    }

}


Solution 2 - Java 8 Thread safe Date Time API

If we really need to stick with SimpleDateFormat we can go ahead with ThreadLocal. But when we have a better option we should consider using it.
Java 8 comes with several Thread safe date classes.

And here is what Java docs says,
"This class is immutable and thread-safe."

It is worth to study more about these classes.
DateTimeFormatterOffsetDateTimeZonedDateTimeLocalDateTimeLocalDateLocalTime


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateUtilsJava8 {

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private DateUtilsJava8() {}

    public static LocalDate parse(String target) {
        return LocalDate.parse(target, DATE_TIME_FORMATTER);
    }

    public static String format(LocalDate target) {
        return target.format(DATE_TIME_FORMATTER);
    }

}


One more thing to note here. It is a good practice to use immutable classes ;)

Complete source code

Happy coding....


No comments:

Post a Comment