SimpleDateFormat 转为线程安全
来源:互联网 发布:jackson 数组转json 编辑:程序博客网 时间:2024/06/06 01:19
多线程调用是会报错。
解决方案:
/**
* 将字符串转换为日期(与时间)
*/
public static Date parseDatetime(String datetime) throws BusinessException {
try {
if (datetime.indexOf(' ') > 0) {
return getSdf("yyyy-MM-dd HH:mm:ss").parse(datetime);
} else {
return getSdf("yyyy-MM-dd").parse(datetime);
}
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(ResultMsg.BEAN_COPY_EXCEPTION, "日期字符串格式错误:" + datetime);
}
}
/**
* 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
*/
public static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
if (tl == null) {
synchronized (lockObj) {
tl = sdfMap.get(pattern);
if (tl == null) {
tl = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
sdfMap.put(pattern, tl);
}
}
}
return tl.get();
}
/** 锁对象 */
private static final Object lockObj = new Object();
/** 存放不同的日期模板格式的sdf的Map */
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();
- SimpleDateFormat 转为线程安全
- SimpleDateFormat非线程安全
- SimpleDateFormat非线程安全
- SimpleDateFormat 非线程安全
- 线程安全之SimpleDateFormat
- SimpleDateFormat线程安全
- SimpleDateFormat非线程安全
- java SimpleDateFormat线程安全
- SimpleDateFormat非线程安全
- 线程安全的 SimpleDateFormat
- SimpleDateFormat 解决非线程安全
- SimpleDateFormat线程安全的问题
- 非线程安全类SimpleDateFormat
- ThreadLocal 解决SimpleDateFormat非线程安全
- ThreadLocal 解决SimpleDateFormat非线程安全
- JDK中的SimpleDateFormat线程非安全
- 从SimpleDateFormat出发去理解线程安全
- SimpleDateFormat 为什么不是线程安全的
- IO流 不用生成文件
- android 平台开机自动重启
- Leetcode|Largest Number
- Android最佳性能实践(一)——合理管理内存
- android获取系统应用大小的方法
- SimpleDateFormat 转为线程安全
- java swing实现简单图片显示(测试生成图片快捷方式)
- typedef和#define的用法与区别
- json数据获取
- Mysql 在windows下切换用户
- WKWebView进度及title
- mac下mysql安装和创建用户权限
- Java多态的内存分析——高淇Java300学习笔记
- Android-使用ViewGroup实现左右滑动切换界面以及界面裂开的效果