使用Threadlocal来解决SimpleDateFormat的多线程安全问题
来源:互联网 发布:怎么看淘宝已下架宝贝 编辑:程序博客网 时间:2024/06/10 07:39
这个文章其实说的很清楚了
下面是实际的代码部分
public class JodaDateService implements DateService { private Map<String, String> timeZoneMapping = ImmutableMap.of("LOH", "Europe/London", "HKH", "Asia/Hong_Kong", "NYH", "America/New_York"); private Map<String, String> cutTimeMapping = ImmutableMap.of("LOH", "23:59", "HKH", "17:00", "NYH", "22:00"); //使用ThreadLocal代替原来的new SimpleDateFormat private static final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>(){ @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; @Override public Date now() { return DateTime.now().toDate(); } @Override public String today(String POGroup) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); return dateFormatter.get().format(new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get(POGroup))).toLocalDateTime().toDate()); } @Override public String getFinancialDate(String POGroup) { String rawCutOffTime = this.cutTimeMapping.get(POGroup); int cutoffHour = Integer.parseInt(rawCutOffTime.split(":")[0]); int cutoffMinute = Integer.parseInt(rawCutOffTime.split(":")[1]); int totalCutOffSeconds = cutoffHour * 3600 + cutoffMinute * 60; DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get(POGroup))); int currentHour = currentDateTime.getHourOfDay(); int currentMinute = currentDateTime.getMinuteOfHour(); int totalCurrentSeconds = currentHour * 3600 + currentMinute * 60 + currentDateTime.getSecondOfMinute(); //这里的new 不是线程安全的 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date result; if (totalCurrentSeconds <= totalCutOffSeconds) { result = currentDateTime.toLocalDateTime().toDate(); } else { result = currentDateTime.plusDays(1).toLocalDateTime().toDate(); }// return dateFormat.format(result); return dateFormatter.get().format(result); }}
0 0
- 使用Threadlocal来解决SimpleDateFormat的多线程安全问题
- ThreadLocal解决SimpleDateFormat线程安全问题
- 用ThreadLocal解决多线程安全问题
- SimpleDateFormat 的线程安全问题与 ThreadLocal
- 一个简单的Java对象池实现——可用来解决SimpleDateFormat的线程安全问题
- Spring使用ThreadLocal解决线程安全问题
- ThreadLocal解决SimpleDateFormat问题
- 使用ThreadLocal解决多线程的并发问题
- 使用ThreadLocal解决多线程的并发问题
- 使用ThreadLocal解决多线程的并发问题
- 使用ThreadLocal解决多线程的并发问题
- 多线程安全问题以及解决安全问题的原理
- SimpleDateFormat的线程安全问题
- SimpleDateFormat的线程安全问题
- SimpleDateFormat的线程安全问题
- SimpleDateFormat 的线程安全问题
- java 解决simpledateformat线程安全问题
- 解决SimpleDateFormat的线程不安全问题的方法:ThreadLocal
- css让图片自适应容器(div)大小
- 字节码操作(javassist)
- android 6.0 SystemUI源码分析(2)-SystemUI启动流程
- 能访问别人电脑,别人无法访问自己电脑的解决办法
- 浪里个浪:Google 北京刚搬进新办公室 走去瞧瞧!
- 使用Threadlocal来解决SimpleDateFormat的多线程安全问题
- CSS基础之样式
- setprecision、fixed、showpoint的用法总结
- new和malloc的10点区别
- #125 Backpack II
- JSP(java)运行时出现“a java exception has occurred”解决方案
- UntiyGUI系统之Button
- android 6.0 SystemUI源码分析(3)-Recent Panel加载显示流程
- 安卓内存泄露