Is SimpleDateFormat is a Threadsafe class ?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.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.
The following code will throw out java.lang.NumberFormatException exception:

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

public class demo 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 {
//Make sdfmt synchronized
System.out.println(sdfmt.parse(strDate));

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

public static void main(String[] args) {
demo[] threads = new demo[20];
for (int i = 0; i != 20; i++) {
threads[i]= new demo();
}
for (int i = 0; i != 20; i++) {
threads[i].start();
} } }
Now we can make it synchronized to prevent this,
synchronized (sdfmt) {
System.out.println(sdfmt.parse(strDate));
}

No comments:

Post a Comment