笑傲网-为创业者提供自媒体学习平台

您现在的位置是: 首页 > 教程资料 > 编程学习

编程学习

SimpleDateFormat线程安全引发的事故以及解决方法

2022-07-24 22:00 编程学习
问题现象同事在多线程中使用了同一个日期的转换工具类,在运行过程中发现日志里偶现一些NumberFormatExcetion,刚开始他以为是数据问题,后来找我仔细分析日志,发现日期字符串存在丢失长度、长度不全等问题,判断是多线程导致,测试代码如下:public class DateTest { //工具类中的日期组件 private static final SimpleDateForm

问题现象

同事在多线程中使用了同一个日期的转换工具类,在运行过程中发现日志里偶现一些NumberFormatExcetion,刚开始他以为是数据问题,后来找我仔细分析日志,发现日期字符串存在丢失长度、长度不全等问题,判断是多线程导致,测试代码如下:

public class DateTest {    //工具类中的日期组件    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    public static void main(String[] args) throws Exception {        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10));        for (int i = 0; i < 100; i++) {            threadPoolExecutor.execute(() -> {                String dateString = sdf.format(new Date());                try {                    Date parseDate = sdf.parse(dateString);                    String dateString2 = sdf.format(parseDate);                    System.out.println(dateString.equals(dateString2));                } catch (Exception e) {                    e.printStackTrace();                }            });        }    }}

打印结果:

原因分析

全局变量的SimpleDateFormat,在并发情况下,存在安全性问题。

我们通过源码看下:

SimpleDateFormat继承了 DateFormat

DateFormat类中维护了一个全局的Calendar变量

sdf.parse(dateStr)和sdf.format(date),都是由Calendar引用来储存的。

如果SimpleDateFormat是static全局共享的,Calendar引用也会被共享。

又因为Calendar内部并没有线程安全机制,所以全局共享的SimpleDateFormat不是线性安全的。

解决方法


解决方式一

「FastDateFormat(FastDateFormat能保证线程安全) 替换 SimpleDateFormat」

private static final FastDateFormat sdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

测试代码如下所示:

public class DateTest {    //工具类中的日期组件//    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    private static final FastDateFormat sdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");    public static void main(String[] args) throws Exception {        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10));        for (int i = 0; i < 100; i++) {            threadPoolExecutor.execute(() -> {                String dateString = sdf.format(new Date());                try {                    Date parseDate = sdf.parse(dateString);                    String dateString2 = sdf.format(parseDate);                    System.out.println(dateString.equals(dateString2));                } catch (Exception e) {                    e.printStackTrace();                }            });        }        threadPoolExecutor.shutdown();    }}

打印结果:

解决方式二

「使用DateTimeFormatter(DateTimeFormatter是线程安全的,java 8+支持)代替SimpleDateFormat」

private static DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

测试代码如下:

public class DateTest {    //工具类中的日期组件//    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    private static DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//    private static final FastDateFormat sdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");    public static void main(String[] args) throws Exception {        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10));        for (int i = 0; i < 100; i++) {            threadPoolExecutor.execute(() -> {                try {                    String dateString = sdf.format(LocalDateTime.now());                    TemporalAccessor temporalAccessor = sdf.parse(dateString);                    String dateString2 = sdf.format(temporalAccessor);                    System.out.println(dateString.equals(dateString2));                } catch (Exception e) {                    e.printStackTrace();                }            });        }        threadPoolExecutor.shutdown();    }}

打印结果如下:

总结

在多线程中使用全局变量时一定要考虑到线程安全问题,若不确定是否存在线程安全问题的公共变量,则不要冒然使用,可以做一些测试和资料分析,或者使用局部变量。




 你在看吗