SimpleDateFormat 线程不安全案例
SimpleDateFormat 线程不安全案例:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Test1 {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Integer count = 10;
Callable<Object> callable = new Callable<Object>() {
@Override
public Object call() throws Exception {
// 线程不安全
return sdf.parse("2019-03-27");
}
};
List<Future<Object>> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
Future<Object> future = executorService.submit(callable);
list.add(future);
}
for (Future<Object> future : list) {
System.out.println(future.get());
}
executorService.shutdown();
}
}
使用ThreadLocal
解决SimpleDateFormat
的线程不安全问题
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatThreadLocal {
private static final ThreadLocal<DateFormat> simpleDateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static Date convert(String str) throws ParseException {
return simpleDateFormat.get().parse(str);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Test2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Integer count = 10;
Callable<Object> callable = new Callable<Object>() {
@Override
public Object call() throws Exception {
return DateFormatThreadLocal.convert("2019-03-27");
}
};
List<Future<Object>> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
Future<Object> future = executorService.submit(callable);
list.add(future);
}
for (Future<Object> future : list) {
System.out.println(future.get());
}
executorService.shutdown();
}
}