Why SimpleDateFormat Is Not Thread‑Safe and How to Fix It in Java
This article explains why Java's SimpleDateFormat is not thread‑safe, demonstrates the problems caused by using a static instance in multithreaded code, and presents four practical solutions—including synchronized blocks, ThreadLocal, and the modern DateTimeFormatter—to ensure correct date handling.
Introduction
In daily development we often use time‑related classes; SimpleDateFormat is familiar for formatting and parsing dates, but it is not thread‑safe. In multithreaded environments it can cause exceptions. This article analyses why SimpleDateFormat is unsafe and presents solutions.
Problem Reproduction
Typical usage defines SimpleDateFormat as a static variable to avoid frequent object creation:
Under single‑threaded execution it works, but in multithreading it produces incorrect times and throws java.lang.NumberFormatException: multiple points .
Root Cause of Thread‑Safety Issue
Because SimpleDateFormat is declared static, its internal Calendar instance is shared among threads. Concurrent threads modify the same Calendar, leading to time discrepancies and crashes. The source of format() shows it uses calendar.setTime(date), which is not isolated per thread.
Date format is not synchronized. It is recommended to create a separate format instance for each thread. If multiple threads access the same format, external synchronization is required.
Solutions
1. Create a new SimpleDateFormat instance where needed instead of using a static variable.
This avoids thread‑safety issues but incurs object‑creation overhead.
2. Use synchronized blocks (simple but may affect performance under high concurrency).
3. Use ThreadLocal to give each thread its own SimpleDateFormat instance.
4. Switch to JDK 1.8+ DateTimeFormatter , which is immutable and thread‑safe.
After applying these changes, the date utility works correctly without errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
