SimpleDateFormat 线程不安全原因及解决办法
程序员文章站
2024-03-15 16:19:24
...
0.翻车演示:
package com.knowledge.system.a_interview.ai_view;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* @program: demo-pom
* @description:
* @author:
* @create: 2020-08-05 18:44
**/
public class ThreadLocalTest {
// private static
public static void main(String[] args) throws ExecutionException, InterruptedException {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Callable<Date> callable=new Callable<Date>() {
@Override
public Date call() throws Exception {
return simpleDateFormat.parse("2020-09-01");
}
};
ExecutorService pool= Executors.newFixedThreadPool(10);
List<FutureTask> futures=new ArrayList<>();
for(int i=0;i<100;i++){
FutureTask task=new FutureTask(callable);
futures.add(task);
pool.submit(task);
}
for (Future future : futures) {
System.out.println(future.get());
}
}
}
1.原因:多线程环境下共享Calendar变量,同时操作calender
format方法:
parse方法:
3.解决办法:
1.ThreadLocal:
package com.knowledge.system.a_interview.ai_view;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* @program: demo-pom
* @description:
* @author:
* @create: 2020-08-05 18:44
**/
public class ThreadLocalTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
Callable<Date> callable = new Callable<Date>() {
@Override
public Date call() throws Exception {
SimpleDateFormat simpleDateFormat = threadLocal.get();
if (null == simpleDateFormat) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
threadLocal.set(simpleDateFormat);
}
return simpleDateFormat.parse("2020-09-01");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<FutureTask> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
FutureTask task = new FutureTask(callable);
futures.add(task);
pool.submit(task);
}
for (Future future : futures) {
System.out.println(future.get());
}
// important
threadLocal.remove();
pool.shutdown();
}
}
上一篇: 笔试题之压缩字符串