The java library SimpleDateFormat (java.text.SimpleDateFormat) cannot be considered thread safe and the programmer should avoid the usage in a multi thread environment.

The problem is based on the way it’s implemented

To fix the problem there are 3 main ways:

  • To create a new instance of SimpleDateFormat for each usage (slow)
  • Sync it properly
  • use FastDateFormat (org.apache.commons.lang3.time.FastDateFormat) that by documentation says : “FastDateFormat is a fast and thread-safe version of java.text.SimpleDateFormat”

Here a main in which is demostrated the issue and the resolution using FastDateFormat

package utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.commons.lang3.time.FastDateFormat;

public class JustMain {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    /* timezone is optional */
    private static final FastDateFormat fastFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
            TimeZone.getTimeZone("GMT"));

    /* problem */
    public static void main(String[] args) {

        List<Thread> threads = new ArrayList<Thread>();

        for (int ii = 0; ii < 1000; ii++) {
            threads.add(new Thread(() -> {
                try {
                    Thread.sleep(10L);
                    System.out.println(sdf.parse("2022-08-05T16:03:11.759Z"));
                    System.out.println(sdf.format(new Date()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }));
        }

        for (Thread thread : threads) {
            thread.start();
        }
    }

    public static void mainFastFormat(String[] args) {

        List<Thread> threads = new ArrayList<Thread>();

        for (int ii = 0; ii < 1000; ii++) {
            threads.add(new Thread(() -> {
                try {
                    Thread.sleep(10L);
                    System.out.println(fastFormat.parse("2022-08-05T16:03:11.759Z"));
                    System.out.println(fastFormat.format(new Date()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }));
        }

        for (Thread thread : threads) {
            thread.start();
        }
    }
}

happy coding

Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.