Why is calling static methods from java.text.DateFormat discouraged?

Question

Why shouldn't I call methods of static java.text.DateFormat?

private static final Date TODAY = Calendar.getInstance().getTime();
private static final DateFormat yymmdd = new SimpleDateFormat("yyMMdd"); 

private String fileName = "file_" + yymmdd.format(TODAY);

Answer

Using static methods from java.text.DateFormat can introduce risks, especially in multi-threaded environments. This is primarily due to the non-thread-safe nature of SimpleDateFormat, which can lead to unexpected behavior or errors when accessed from multiple threads.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

public class DateUtils {
    private static final ThreadLocal<DateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyMMdd"));

    public static String getFormattedDate() {
        Date today = Calendar.getInstance().getTime();
        return "file_" + dateFormat.get().format(today);
    }
}

Causes

  • SimpleDateFormat is not thread-safe, which can lead to data corruption when accessed concurrently.
  • Instances of SimpleDateFormat maintain their internal state, which can be modified during formatting, causing inaccuracies.
  • Find Bugs may flag this because static fields can lead to shared state issues across different classes or threads.

Solutions

  • Use ThreadLocal to maintain separate instances of SimpleDateFormat for each thread.
  • Switch to java.time.format.DateTimeFormatter from Java 8, which is immutable and thread-safe.
  • Create a utility method for date formatting that ensures each call uses a fresh instance of SimpleDateFormat.

Common Mistakes

Mistake: Using a single instance of SimpleDateFormat across multiple threads.

Solution: Implement ThreadLocal to ensure each thread uses its unique instance.

Mistake: Neglecting the potential for concurrent modification of static date formatters.

Solution: Prefer java.time classes which are designed to be immutable and thread-safe.

Helpers

  • java.text.DateFormat
  • SimpleDateFormat
  • thread safety
  • Java date formatting
  • FindBugs static method warning
  • java.time.format.DateTimeFormatter

Related Questions

⦿How to Permanently Increase Java Heap Size for JVM on Your Computer?

Learn how to set a permanent Java heap size avoiding the need to use Xmx argument with every command.

⦿How to Automatically Scroll a JTable to the Bottom When a New Row is Added

Learn how to automatically scroll a JTable to the bottom in Java Swing when new rows are added to your applications table.

⦿How to Perform Union and Intersection of Sets in Java

Learn simple and effective methods to perform union and intersection operations on Java Sets with code examples.

⦿How to Capture a Screenshot in Java?

Learn how to take a screenshot in Java including complete code snippets and common mistakes to avoid.

⦿How to Enable TLS 1.2 Support in Java 6

Learn how to enable TLS 1.2 in Java 6 including patches updates and best practices for secure communication.

⦿What is the Difference Between offer() and add() Methods in Java PriorityQueue?

Explore the key differences between the offer and add methods in Javas PriorityQueue along with code examples and common mistakes.

⦿How to Resolve 'Target Process Not Responding' Error with jstack on Ubuntu?

Learn how to fix the target process not responding error when using jstack on Ubuntus Tomcat server and streamline Java thread dumps.

⦿How to Change Text Alignment in JavaFX TableView Columns

Learn how to adjust column text alignment in JavaFX TableView using CSS and Java code.

⦿How to Open a Folder in File Explorer Using Java Cross-Platform

Learn how to open a specific folder in the file explorer using Java in a crossplatform manner including code snippets and troubleshooting tips.

⦿Why Does Hibernate's query.list() Method Return an Empty List Instead of Null?

Discover why Hibernates query.list returns an empty list instead of null and how to handle this in your applications.

© Copyright 2025 - CodingTechRoom.com