芝麻_糊

导航

SimpleDateFormat的安全问题解决方法

问题:

SimpleDateFormat 是线程不安全的类,一般不要定义为static变量,如果定义为static,必须加锁,或者使用DateUtils工具类。

而且SimpleDateFormat 中的parse(String str)解析时不能为 "",否则会有ParseException

解决方法:

[正例]:

1.注意线程安全,使用DateUtils。

2.亦推荐如下处理:

 1 private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {      
 2 
 3  @Override       
 4 
 5 protected DateFormat initialValue() {           
 6 
 7 return new SimpleDateFormat("yyyy-MM-dd");       
 8 
 9 }   
10 
11 };   

3.说明:如果是JDK8的应用,可以使用Instant代替DateLocalDateTime代替CalendarDateTimeFormatter代替Simpledateformatter,官方给出的解释:simple beautiful strong immutable thread-safe

[正例]

System.out.println(LocalDate.of(2017, 6, 7));

System.out.println(LocalTime.of(3, 20, 15));

System.out.println(LocalDateTime.of(2017, 6, 7,3, 20, 15));

System.out.println(Instant.now().atOffset(ZoneOffset.ofHours(8)));

返回结果:

2017-06-07

03:20:15

2017-06-07T03:20:15

2017-06-07T11:37:15.815+08:00

有篇文章分析的不错http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

posted on 2017-09-02 17:27  芝麻_糊  阅读(761)  评论(0编辑  收藏  举报