ThreadLocal for per-thread data
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ThreadLocal is a variable where every thread has its own separate value. If you cannot share an object safely and cannot make it immutable, giving each thread its own copy removes the sharing, and with it the race.
SimpleDateFormat is not thread-safe
SimpleDateFormat (from java.text, the old date API) keeps working data inside itself, in a Calendar field, while it parses or formats. If two threads use the same object at once, they overwrite each other's working data.
Example 1 · Mistake: one SimpleDateFormat shared by four threads
import java.text.SimpleDateFormat;import java.util.Date;
public class SharedFormatDemo { static final SimpleDateFormat FORMAT = new SimpleDateFormat("dd-MM-yyyy"); // shared: unsafe static int wrong = 0; static int crashed = 0;
static synchronized void addWrong() { wrong++; }
static synchronized void addCrash() { crashed++; }
public static void main(String[] args) throws InterruptedException { String[] dates = {"15-08-2024", "26-01-2025", "02-10-2023", "14-11-2022"}; Thread[] workers = new Thread[4]; for (int t = 0; t < 4; t++) { String text = dates[t]; workers[t] = new Thread(() -> { for (int i = 0; i < 2000; i++) { try { Date d = FORMAT.parse(text); if (!FORMAT.format(d).equals(text)) { addWrong(); // parsed or formatted the wrong date } } catch (Exception e) { addCrash(); // NumberFormatException and friends } } }, "worker-" + (t + 1)); workers[t].start(); } for (Thread w : workers) { w.join(); } System.out.println("checks: 8000"); System.out.println("wrong results: " + wrong); System.out.println("exceptions: " + crashed); }}checks: 8000 wrong results: 2772 exceptions: 1305
What this code does
- Each thread parses its own date and formats it back, so every check should pass. Because the four threads share one formatter's working data, thousands of checks give a different date or throw. The numbers change on every run.
- Nothing in the code looks wrong in a single-threaded test, which is why this bug often reaches production.
The result is not always a crash. Often you get a wrong date with no error at all, which is the worst kind of bug in a fee receipt or a ticket. DecimalFormat and the old Calendar class have the same problem.
static final SimpleDateFormat shared by a whole web app is a classic production bug. final only stops the reference from changing, not the object.ThreadLocal.withInitial: one copy per thread
ThreadLocal.withInitial(supplier) creates a ThreadLocal whose value is built by the supplier the first time each thread calls get(). After that, get() returns that thread's own object, and set(value) changes only that thread's value.
static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("dd-MM-yyyy"));
Date d = FORMAT.get().parse("15-08-2024"); // this thread's own formatter
static final ThreadLocal<String> USER = new ThreadLocal<>(); // starts as nullUSER.set("Priya");USER.get(); // "Priya" in this thread onlyUSER.remove(); // clear this thread's valueWith 4 threads you get 4 formatters, no matter how many dates they parse. No locks are needed, because no object is ever used by two threads.
Example 2 · Fix with ThreadLocal: one formatter per thread
import java.text.SimpleDateFormat;import java.util.Date;
public class ThreadLocalFormatDemo { static int created = 0; static int wrong = 0; static int crashed = 0;
static synchronized void addCreated() { created++; }
static synchronized void addWrong() { wrong++; }
static synchronized void addCrash() { crashed++; }
static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> { addCreated(); // runs once per thread return new SimpleDateFormat("dd-MM-yyyy"); });
public static void main(String[] args) throws InterruptedException { String[] dates = {"15-08-2024", "26-01-2025", "02-10-2023", "14-11-2022"}; Thread[] workers = new Thread[4]; for (int t = 0; t < 4; t++) { String text = dates[t]; workers[t] = new Thread(() -> { SimpleDateFormat mine = FORMAT.get(); // this thread's own formatter for (int i = 0; i < 2000; i++) { try { Date d = mine.parse(text); if (!mine.format(d).equals(text)) { addWrong(); } } catch (Exception e) { addCrash(); } } }, "worker-" + (t + 1)); workers[t].start(); } for (Thread w : workers) { w.join(); } System.out.println("checks: 8000"); System.out.println("wrong results: " + wrong); System.out.println("exceptions: " + crashed); System.out.println("formatters created: " + created); }}checks: 8000 wrong results: 0 exceptions: 0 formatters created: 4
What this code does
FORMAT.get()returns this thread's ownSimpleDateFormat, built bywithInitialon the thread's first call. Every check passes on every run.- Exactly four formatters were created for 8,000 checks: one per thread, not one per date.
The same tool carries per-request context: the logged-in user or a request id, set once when a request starts and read deep inside other methods without passing it as a parameter. Web frameworks do this for you behind the scenes.
Trace the code
Two threads, two copies of one ThreadLocal
Watch how main and the worker each keep their own value.
Variables
- mainCopy
- 1
Output
(nothing printed yet)Line 5main reads its own copy (0, the starting value) and stores 1 in it.
Calling remove() when threads are reused
Thread reuse means one thread runs many tasks, one after another. Thread pools work this way (the Executors and Thread Pools module covers them), and so do the worker threads of web servers.
Example 3 · Mistake: a reused thread remembers the last user
public class ForgottenRemoveDemo { static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
static void handle(String page, String loggedInUser) { if (loggedInUser != null) { CURRENT_USER.set(loggedInUser); } String user = CURRENT_USER.get(); String who = (user == null) ? "guest" : user; System.out.println(Thread.currentThread().getName() + ": " + page + " for " + who); // bug: no CURRENT_USER.remove() }
public static void main(String[] args) throws InterruptedException { String[][] requests = { {"/cart", "Priya"}, {"/cart", null}, // a guest: should see an empty cart {"/orders", null} // another guest };
Thread worker = new Thread(() -> { for (String[] r : requests) { handle(r[0], r[1]); } }, "worker-1"); worker.start(); worker.join(); }}worker-1: /cart for Priya worker-1: /cart for Priya worker-1: /orders for Priya
What this code does
worker-1handles three requests one after another, like a pool thread. Priya's name was set during the first request and never removed, so both guest requests are served as Priya.- In a real shop app, that would show Priya's cart and orders to strangers: a data leak, plus a memory leak if the value is large.
Example 4 · The fix: remove() in finally
public class RemoveInFinallyDemo { static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
static void handle(String page, String loggedInUser) { if (loggedInUser != null) { CURRENT_USER.set(loggedInUser); } try { String user = CURRENT_USER.get(); String who = (user == null) ? "guest" : user; System.out.println(Thread.currentThread().getName() + ": " + page + " for " + who); } finally { CURRENT_USER.remove(); // always clean up, even after an exception } }
public static void main(String[] args) throws InterruptedException { String[][] requests = { {"/cart", "Priya"}, {"/cart", null}, {"/orders", null} };
Thread worker = new Thread(() -> { for (String[] r : requests) { handle(r[0], r[1]); } }, "worker-1"); worker.start(); worker.join(); }}worker-1: /cart for Priya worker-1: /cart for guest worker-1: /orders for guest
What this code does
CURRENT_USER.remove()runs at the end of every request, even if the work throws, so the next request on the same thread starts with no user.remove()clears only the calling thread's value; other threads' values are not touched.
A ThreadLocal value set during one task is still there when the same thread starts the next task. That causes two problems. A data leak: the next request can see the previous user's data. A memory leak: the value lives as long as the thread, which for a pool thread can be the whole life of the server, so large objects are never freed.
The fix is a habit: set the value, then do the work inside try, and call remove() in finally, so it runs even when the work throws an exception.
DateTimeFormatter as the simpler fix
DateTimeFormatter (from java.time, Java 8) is immutable and thread-safe. One static final formatter can be shared by every thread, with no ThreadLocal and no locks, exactly like the immutable objects from the last lesson.
Example 5 · DateTimeFormatter: share one, no ThreadLocal needed
import java.time.LocalDate;import java.time.format.DateTimeFormatter;
public class DateTimeFormatterDemo { static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // immutable static int wrong = 0;
static synchronized void addWrong() { wrong++; }
public static void main(String[] args) throws InterruptedException { String[] dates = {"15-08-2024", "26-01-2025", "02-10-2023", "14-11-2022"}; Thread[] workers = new Thread[4]; for (int t = 0; t < 4; t++) { String text = dates[t]; workers[t] = new Thread(() -> { for (int i = 0; i < 2000; i++) { LocalDate d = LocalDate.parse(text, FORMAT); if (!d.format(FORMAT).equals(text)) { addWrong(); } } }, "worker-" + (t + 1)); workers[t].start(); } for (Thread w : workers) { w.join(); } System.out.println("checks: 8000"); System.out.println("wrong results: " + wrong);
LocalDate admission = LocalDate.parse("15-08-2025", FORMAT); System.out.println("fee due on: " + admission.plusDays(30).format(FORMAT)); }}checks: 8000 wrong results: 0 fee due on: 14-09-2025
What this code does
- The same 8,000 checks with one shared
DateTimeFormatterall pass, with no locks and no ThreadLocal, because the formatter is immutable. LocalDateis immutable too:plusDays(30)returns a new date and leavesadmissionunchanged.
- Object is immutable (
DateTimeFormatter,String, records): share one copy. - Object is mutable and cheap to create: create a new one inside the method.
- Object is mutable and costly to create, used very often:
ThreadLocal.withInitial. - Per-request context in a reused thread:
ThreadLocalwithremove()infinally.
So the best fix for date formatting is to move to java.time: LocalDate.parse(text, FORMAT) and date.format(FORMAT). Keep ThreadLocal for objects that really must be mutable per thread, and for per-request context.
Next step
Check your understanding
11 quick questions