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 uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- How to Use Updatable ResultSet in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?