利用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);
    }


}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM