LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 7

ThreadLocal for a non-thread-safe formatter in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

SimpleDateFormat is not thread-safe. Give each of three threads its own instance with ThreadLocal, format the same fixed timestamp in each thread with a different pattern, and print the results after joining.

Solution
Main.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        return f;
    });

    public static void main(String[] args) throws InterruptedException {
        Date moment = new Date(1_767_225_600_000L);          // 2026-01-01T00:00:00Z
        String[] patterns = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm", "EEE, d MMM yyyy"};
        String[] results = new String[patterns.length];
        int[] identities = new int[patterns.length];
        Thread[] ts = new Thread[patterns.length];
        for (int i = 0; i < ts.length; i++) {
            int idx = i;
            ts[i] = new Thread(() -> {
                SimpleDateFormat f = FORMAT.get();           // this thread's own instance
                f.applyPattern(patterns[idx]);
                results[idx] = f.format(moment);
                identities[idx] = System.identityHashCode(f);
                FORMAT.remove();                              // good hygiene, especially in thread pools
            });
            ts[i].start();
        }
        for (Thread t : ts) t.join();
        for (String r : results) System.out.println(r);
        System.out.println("separate instances: " + (identities[0] != identities[1] && identities[1] != identities[2]));
        System.out.println("main still has the default pattern: " + FORMAT.get().format(moment));
    }
}

Output Verified by compiling and running

01/01/2026
2026-01-01 00:00
Thu, 1 Jan 2026
separate instances: true
main still has the default pattern: 2026-01-01

Changing the pattern in one thread cannot affect another, because each thread has its own formatter. (In new code prefer the immutable, thread-safe java.time.DateTimeFormatter.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links