考慮到SimpleDateFormat為線程不安全對象,故應用ThreadLocal來解決,使SimpleDateFormat從獨享變量變成單個線程變量。
ThreadLocal用於處理某個線程共享變量:對於同一個static ThreadLocal,不同線程只能從中get,set,remove自己的變量,而不會影響其他線程的變量。
- get()方法是用來獲取ThreadLocal在當前線程中保存的變量副本;
- set()用來設置當前線程中變量的副本;
- remove()用來移除當前線程中變量的副本;
- 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); } }