--
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(); } } }
Format is also not thread safe, so you have to watch how you convert a Date to String as well.
ReplyDeleteNote: Joda Time formatter doesn't have this problem.