博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程安全日期格式化操作的几种方式
阅读量:6886 次
发布时间:2019-06-27

本文共 1920 字,大约阅读时间需要 6 分钟。

线程安全日期格式化操作的几种方式

由于 DateFormat 是非线程安全的,因此在多线程并发情况下日期格式化时需要特别注意。下面记录几种格式化的方式:

线程不安全的处理方式

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//线程不安全

这种方式会报如下异常:

java.lang.NumberFormatException: For input string: ""    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)    at java.lang.Long.parseLong(Long.java:601)    at java.lang.Long.parseLong(Long.java:631)    at java.text.DigitList.getLong(DigitList.java:195)    at java.text.DecimalFormat.parse(DecimalFormat.java:2051)    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)    at java.text.DateFormat.parse(DateFormat.java:364)    at com.concurrent.DateUtils.parse(DateUtils.java:28)    at com.concurrent.DateUtils$2.run(DateUtils.java:42)    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)    at java.lang.Thread.run(Thread.java:745)

线程安全的处理方式

方式一,每次new一个对象

public static Date parse(String date) throws ParseException {        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);}

方式二,通过ThreadLocal进行处理

private static final ThreadLocal
LOCAL_DATE_FORMAT = new ThreadLocal
(){ @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } };
  • 如果是JDK7及以下的应用,可用ThreadLocal的方式

方式三,java8 通过 DateTimeFormatter 进行处理

private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(date, DATE_TIME_FORMATTER);LOCAL_DATE_FORMAT.get().parse(date);
  • 如果是JDK8的应用,可以使用instant代替Date,Localdatetime代替Calendar,Datetimeformatter代替Simpledateformatter,官方给出的解释:simple beautiful strong immutable thread-safe。

转载地址:http://rtabl.baihongyu.com/

你可能感兴趣的文章
多线程 打字练习
查看>>
[BSGS]
查看>>
day19-2 生成器,递归函数
查看>>
未能加载文件或程序集“Enyim.Caching”或它的某一个依赖项。未能验证强名称签名...
查看>>
设计模式——面向对象设计原则
查看>>
mysql安装
查看>>
301、302跳转与200状态码
查看>>
小波变化库——Pywalvets学习笔记
查看>>
y - 1,一个 缝隙,
查看>>
2维矩阵前缀和技巧题目
查看>>
关于git的一些操作
查看>>
[原]RobotFrameWork(四)变量运算与Evaluate
查看>>
心态决定命运_no excuses, suck it up, obey your teacher
查看>>
【HDOJ】2371 Decode the Strings
查看>>
【HDOJ】1818 It's not a Bug, It's a Feature!
查看>>
java环境变量
查看>>
180510.最近踩过和听过的sql的坑
查看>>
FastSocket学习笔记~RPC的思想,面向对象的灵活
查看>>
TCP连接探测中的Keepalive 和心跳包
查看>>
2015第5周三网摘
查看>>