ThreadLocal的一个经典案例,将线程不安全的 SimpleDateFormat 类封装成线程安全的:
参考地址1:https://www.cnblogs.com/shuiyj/p/13185060.html
参考地址2:https://blog.csdn.net/YLG_1300710336/article/details/82314328
package stream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 线程安全的日期工具类
* @author zx
* @date 2020年11月03日
*/
public class CurrentDateUtil {
/**
* 默认格式化模式
*/
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 非默认格式化选用格式常量
*/
public static final String FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
/**
* ThreadLocal 持有当前线程的format对象
*/
private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL_DATE_FORMAT = ThreadLocal.withInitial(SimpleDateFormat::new);
/**
* 设置格式化pattern,自定义格式化格式时使用
* @param pattern 格式化pattern
*/
private static void setPattern(String pattern){
THREAD_LOCAL_DATE_FORMAT.get().applyPattern(pattern);
}
/**
* 使用默认format对象,默认转换为 yyyy-MM-dd HH:mm:ss 格式
* @param date 日期参数,不能为空,空则抛出异常
* @return 转换完成的 yyyy-MM-dd HH:mm:ss 字符串
*/
public static String format(Date date) throws Exception{
return format(date, DEFAULT_FORMAT);
}
/**
* 根据传入的pattern设置
* @param date 日期参数,不能为空,空则抛出异常
* @param pattern 自定义的格式化pattern字符串
* @return String
*/
public static String format(Date date, String pattern) throws Exception {
if(date == null ){
throw new IllegalArgumentException("param date should not be null ! ");
}
if(pattern == null || "".equals(pattern)){
throw new IllegalArgumentException("param pattern should not be null !");
}
setPattern(pattern);
return THREAD_LOCAL_DATE_FORMAT.get().format(date);
}
/**
* 使用默认的pattern,将字符串转Date类型
* @param dateStr 日期字符串
* @return 转换后的日期对象
*/
public static Date parse(String dateStr) throws Exception{
return parse(dateStr, DEFAULT_FORMAT);
}
/**
* 使用手动设置的的pattern,将字符串转Date类型
* @param dateStr 日期字符串
* @param pattern 自定义的格式化pattern字符串
* @return 格式化后的日期类型
*/
public static Date parse(String dateStr, String pattern) throws Exception {
if(dateStr == null || "".equals(dateStr) ){
throw new IllegalArgumentException("param dateStr should not be null ! ");
}
if(pattern == null || "".equals(pattern)){
throw new IllegalArgumentException("param pattern should not be null !");
}
setPattern(pattern);
return THREAD_LOCAL_DATE_FORMAT.get().parse(dateStr);
}
}