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
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?
- What is runtime polymorphism in Java?
- How to add BASIC Authentication into HttpURLConnection?
- What is String literal pool?
- Can the run() method be called directly to start a thread?
- What does Class.forname method do?
- How to read input from console (keyboard) in Java?