I have tried to write an example to show SimpleDateFormat is thread unsafe. but it does not work! Can anyone give me an example of showing SimpleDateFormat is thread unsafe?
public static void main(String[] args) throws ParseException, InterruptedException {
Date aDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-12-15 23:59:59"));
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DataFormatter callable = new DataFormatter(sdf, aDate);
Collection<DataFormatter> callables = Collections.nCopies(1000, callable);
executor.invokeAll(callables);
executor.shutdown();
}
private static class DataFormatter implements Callable<String> {
private SimpleDateFormat sdf;
private Date aDate;
public DataFormatter(SimpleDateFormat sdf, Date aDate) {
this.sdf = sdf;
this.aDate = aDate;
}
@Override
public String call() throws Exception {
String format = sdf.format(aDate);
Assert.assertEquals("2016-12-15 23:59:59", format);
return format;
}
}