FAQ

Java

JSP

Servlet


Advertisement



Is SimpleDateFormat Thread-Safe Class?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. From time to time, you will use SimpleDateFormat class in your project. But Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. Yes, it is not thread-safe object as long as your read the whole documentation of the SimpleDateFormat class Java API. The following code will throw out java.lang.NumberFormatException exception:

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample extends Thread {

private static SimpleDateFormat sdfmt = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy");

public void run() {
Date now = new Date();
String strDate = now.toString();
int m = 3;
while (m--!=0) {
try {
sdfmt.parse(strDate);
}
catch(Exception e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
SimpleDateFormatExample[] threads = new SimpleDateFormatExample[20];
for (int i = 0; i != 20; i++) {
threads[i]= new SimpleDateFormatExample();
}
for (int i = 0; i != 20; i++) {
threads[i].start();
}
}

}

Using synchronized block can solve this problem:

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample extends Thread {

private static SimpleDateFormat sdfmt = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy");

public void run() {
Date now = new Date();
String strDate = now.toString();
int m = 3;
while (m--!=0) {
try {
synchronized(sdfmt) {
sdfmt.parse(strDate);
}

}
catch(Exception e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
SimpleDateFormatExample[] threads = new SimpleDateFormatExample[20];
for (int i = 0; i != 20; i++) {
threads[i]= new SimpleDateFormatExample();
}
for (int i = 0; i != 20; i++) {
threads[i].start();
}
}

}

For synchronized keyword in Java, please read How to use the synchronized keyword? . You also can find different implementations to make SimpleDateFormat thread safe in here


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |