threadlocal解决SimpleDateFormat线程安全问题

背景:某些局部函数,

如果用静态变量,则会有线程安全问题,

如果用局部变量,则会有资源浪费

 

解决方案:

1. 同步

2. threadlocal

//    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static ThreadLocal<SimpleDateFormat> localDateFormat = new ThreadLocal<>();

    private LogUrlUtil() {
        localDateFormat.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    private static StringBuilder date = new StringBuilder(50);

    /**
     * 寻找含有Switching to a new log的行,取得
     * @param line
     * @return
     */
    private static final String FLAG_STRING = "Switching to a new log";

    public static Pair<Date, String> getLastLogUrl(String line) throws ParseException {

        if(line == null || "".equals(line)) {
            return null;
        }

        if(-1 == line.indexOf(FLAG_STRING)) {
            return null;
        }

        String [] items = line.split("'");
        return new Pair<Date,String>(localDateFormat.get().parse(items[0].substring(0,23)), items[1]);

  

posted on 2018-08-16 15:36  silyvin  阅读(965)  评论(0)    收藏  举报