SimpleDateFormat和DateFormat类不是线程安全的。
2015-11-23 00:00
525 查看
摘要: JDK原始文档如下:
Synchronization:
Date formats are not synchronized.
It is recommended to create separate format instances for each thread.
If multiple threads access a format concurrently, it must be synchronized externally.
比较好的两种方法
Synchronization:
Date formats are not synchronized.
It is recommended to create separate format instances for each thread.
If multiple threads access a format concurrently, it must be synchronized externally.
比较好的两种方法
import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ConcurrentDateUtil { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static Date parse(String dateStr) throws ParseException { return threadLocal.get().parse(dateStr); } public static String format(Date date) { return threadLocal.get().format(date); } }
import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ThreadLocalDateUtil { private static final String date_format = "yyyy-MM-dd HH:mm:ss"; private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); public static DateFormat getDateFormat() { DateFormat df = threadLocal.get(); if(df==null){ df = new SimpleDateFormat(date_format); threadLocal.set(df); } return df; } public static String formatDate(Date date) throws ParseException { return getDateFormat().format(date); } public static Date parse(String strDate) throws ParseException { return getDateFormat().parse(strDate); } }
相关文章推荐
- php执行msyql脚本 sql文件
- ViewPager如下效果你研究过吗?
- vbox 中复制不可以用
- android 开发环境 ubuntu 12.04
- python-02:学习路线
- python-03:用最简单快速的方法入门
- ABC输出BCA
- Mac磁盘诊断怎么通过EasyRecovery实现
- 常用命令
- 进驻开源中国博客
- ABBYY FineReader都有哪些大用途
- iMindMap画布的灵活运用
- ios 集成环信的坑
- ie11开发者工具打开一片空白问题
- 月薪过万不是梦,IT就业前景分析
- CSS3的滤镜效果(-webkit-filter)
- 网易云加密
- dwr 使用小结
- 事务日志
- MySQL中的事务日志