Synchronizing access to SimpleDateFormat
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
SimpleDateFormat is not thread-safe in Java. Sharing a single instance across threads without synchronization produces corrupted dates, wrong values, or NumberFormatException. The best fix in modern Java (8+) is to replace SimpleDateFormat with DateTimeFormatter, which is immutable and thread-safe. If you must use SimpleDateFormat, the options are: ThreadLocal<SimpleDateFormat>, explicit synchronized blocks, or creating a new instance per use. ThreadLocal gives the best performance; creating new instances is the simplest.
The Problem
SimpleDateFormat uses internal mutable fields (calendar, numberFormat) during format() and parse(). When two threads call format() simultaneously, they overwrite each other's intermediate state, producing garbage output like "2025-03-2025" or throwing ArrayIndexOutOfBoundsException.
Solution 1: DateTimeFormatter (Best — Java 8+)
Solution 2: ThreadLocal
Each thread gets its own SimpleDateFormat instance, eliminating contention. The instance is created lazily on first access and reused for subsequent calls on the same thread.
Solution 3: synchronized Block
Simple but creates a bottleneck — only one thread can format/parse at a time. Acceptable for low-contention scenarios.
Solution 4: New Instance Per Call
The simplest approach but creates garbage for the GC on every call. Acceptable if formatting is infrequent.
Performance Comparison
Migrating from SimpleDateFormat to DateTimeFormatter
Common Pitfalls
- Sharing a
SimpleDateFormatinstance as a static field: This is the root cause. Anystatic final SimpleDateFormataccessed from multiple threads is a data race. Either replace withDateTimeFormatter, wrap inThreadLocal, or add synchronization. A single production incident from this bug can produce silently wrong dates in database records. - Using
ThreadLocalin thread pools without cleanup: In application servers and thread pools, threads are reused. IfThreadLocalholds aSimpleDateFormatwith a modified time zone or locale, subsequent requests on the same thread inherit stale settings. CallThreadLocal.remove()in afinallyblock when the scope ends. - Forgetting that
DateTimeFormatter.ofPatternis locale-sensitive:DateTimeFormatter.ofPattern("MMM dd")uses the JVM's default locale for month names. On a server withLocale.JAPAN, "Mar" becomes "3月". UseDateTimeFormatter.ofPattern("MMM dd", Locale.US)for consistent English output. - Mixing
java.util.Dateandjava.timeAPIs carelessly: Converting betweenDateandLocalDateTimerequires a timezone (ZoneId).Date.toInstant()gives UTC, butLocalDateTimehas no timezone. UseZonedDateTimeor specifyZoneId.of("UTC")explicitly to avoid off-by-hours bugs. - Synchronized block scope too broad: Synchronizing an entire method that does I/O or computation beyond date formatting creates unnecessary contention. Synchronize only the
format()/parse()call, not the surrounding logic.
Summary
SimpleDateFormatis not thread-safe — never share a single instance across threads without protection- Use
DateTimeFormatter(Java 8+) as the default replacement — it is immutable and thread-safe - Use
ThreadLocal<SimpleDateFormat>if you must stay on the old API for performance with thread safety synchronizedblocks work but create contention under high load- Migrate from
java.util.Date+SimpleDateFormattojava.time+DateTimeFormatterfor new code
Related reading
- synchronizing audio over a network
- Synchronizing data from MSSQL to Elasticsearch using Apache Kafka
- Synchronizing keyspaces in new cassandra datacenter
- Synchronous and Asynchronous data transmission between client and server
- Syncing multiple asynchronous requests in Java
- Syntax for creating a two-dimensional array in Java
- Synchronous architecture with asynchronous repository
- Synchronous I/O within an async/await-based Windows Service

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.