版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Megustas_JJC/article/details/83990109
ThreadLocal类维持线程封闭性,可以使线程中的某个值与保存值得对象关联起来。为每个使用该变量的线程都存有一份独立的脚本,因此get总是返回当前执行线程在调用set时设置的最新值。
ThreadLocal对象通常用于防止对可变的单实例变量(Singleton)或全局变量进行共享(在多线程应用程序在没有协同的情况下使用全局变量时,就不是线程安全的)
深入理解Java:SimpleDateFormat安全的时间格式化
SimpleDateFormat类的非线程安全:
public class MTAuth {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
// SimpleDateFormat 这个是非线程安全的
private static SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
public static String getAuthDate(Date date) {
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateString = df.format(date);
return dateString;
}
}
线程安全:
public class DwUtil {
private static final Logger LOG = LoggerFactory.getLogger(DwUtil.class.getName());
private static ThreadLocal<SimpleDateFormat> local1 = new ThreadLocal<SimpleDateFormat>();
private static ThreadLocal<SimpleDateFormat> local2 = new ThreadLocal<SimpleDateFormat>();
public static Date parseDate(String str, boolean lenient) {
SimpleDateFormat sdf = local1.get();
if (sdf == null) {
sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
local1.set(sdf);
}
try {
sdf.setLenient(lenient);
return sdf.parse(str);
} catch (Exception e) {
return null;
}
}
public static String formatDate(Date date) {
SimpleDateFormat sdf = local1.get();
if (sdf == null) {
sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
local1.set(sdf);
}
return sdf.format(date);
}
}