Article directory
foreword
A java.lang.NumberFormatException problem occurs when using SimpleDateFormat for date conversion in a multi-threaded situation.
1. SimpleDateFormat for date conversion
code show as below:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0; i < 10; i++){
new Thread(() -> {
try {
log.debug("{}",sdf.parse("1995-09-04"));//log是使用了@Self4j注解
}catch (Exception e){
log.error("{}",e);
}
}).start();
}
This code is likely to have java.lang.NumberFormatException problems or incorrect date parsing results, because SimpleDateFormat is not thread-safe.
2. Solution 1: DateTimeFormatter provided by java8
code show as below:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for(int i = 0; i < 10; i++){
new Thread(() -> {
LocalDate date = dtf.parse("1995-09-04",LocalDate::form);
log.debug("{}",date);
}).start();
}
You can see that this class is immutable and thread-safe.
3. Solution 2
code show as below:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0; i < 10; i++){
new Thread(() -> {
synchronize (sdf){
try {
log.debug("{}",sdf.parse("1995-09-04"));//log是使用了@Self4j注解
}catch (Exception e){
log.error("{}",e);
}
}
}).start();
}
Although this can solve the problem, it will cause a loss in performance, so it is not recommended to use it. It is recommended to use method 1.