使用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