我想向同事展示SimpleDateFormat是而不是通過簡單的JUnit測試可確保線程安全。下面的類沒有使我的觀點(在多線程環境中重用SimpleDateFormat),我不明白爲什麼。你能發現什麼阻止了我使用SDF拋出運行時異常嗎?證明SimpleDateFormat不是線程安全的
public class SimpleDateFormatThreadTest
{
@Test
public void test_SimpleDateFormat_MultiThreaded() throws ParseException{
Date aDate = (new SimpleDateFormat("dd/MM/yyyy").parse("31/12/1999"));
DataFormatter callable = new DataFormatter(aDate);
ExecutorService executor = Executors.newFixedThreadPool(1000);
Collection<DataFormatter> callables = Collections.nCopies(1000, callable);
try{
List<Future<String>> futures = executor.invokeAll(callables);
for (Future f : futures){
try{
assertEquals("31/12/1999", (String) f.get());
}
catch (ExecutionException e){
e.printStackTrace();
}
}
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
class DataFormatter implements Callable<String>{
static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date;
DataFormatter(Date date){
this.date = date;
}
@Override
public String call() throws RuntimeException{
try{
return sdf.format(date);
}
catch (RuntimeException e){
e.printStackTrace();
return "EXCEPTION";
}
}
}
你應該告訴你的同事閱讀javadoc,以便繼續做一些適當的工作! –
是的SimpleDateFormat不是線程安全的,我們(壞)的經驗是,它不會拋出異常,它執行瘋狂的格式(實際上更糟糕)。嘗試在代碼中輸出值。 –
爲每個線程創建另一個SDF並對其進行格式化。然後比較輸出並在輸出不匹配時拋出異常。 – Stefan