利用threadlocal解决SimpleDateFormat解决线程不安全的问题

考虑到SimpleDateFormat为线程不安全对象,故应用ThreadLocal来解决,使SimpleDateFormat从独享变量变成单个线程变量。
ThreadLocal用于处理某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。
  1. get()方法是用来获取ThreadLocal在当前线程中保存的变量副本;
  2. set()用来设置当前线程中变量的副本;
  3. remove()用来移除当前线程中变量的副本;
  4. initialValue()方法修改初始值;
 
package com.tanlu.user.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 考虑到SimpleDateFormat为线程不安全对象,故应用ThreadLocal来解决,
 * 使SimpleDateFormat从独享变量变成单个线程变量
 */
public class ThreadLocalDateUtil {

    //写法1:
    /*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);
    }*/


    //写法2:
    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);
    }


}
 

猜你喜欢

转载自www.cnblogs.com/chaiming520/p/11089943.html