這篇文章主要為大家展示了“java的SimpleDateFormat線程不安全怎么辦”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“java的SimpleDateFormat線程不安全怎么辦”這篇文章吧。
在java8以前,要格式化日期時間,就需要用到SimpleDateFormat。
但我們知道SimpleDateFormat是線程不安全的,處理時要特別小心,要加鎖或者不能定義為static,要在方法內new出對象,再進行格式化。很麻煩,而且重復地new出對象,也加大了內存開銷。
來看看SimpleDateFormat的源碼,先看format方法:
// Called from Format after creating a FieldDelegate
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// Convert input date to time field list
calendar.setTime(date);
...
}問題就出在成員變量calendar,如果在使用SimpleDateFormat時,用static定義,那SimpleDateFormat變成了共享變量。那SimpleDateFormat中的calendar就可以被多個線程訪問到。
SimpleDateFormat的parse方法也是線程不安全的:
public Date parse(String text, ParsePosition pos)
{
...
Date parsedDate;
try {
parsedDate = calb.establish(calendar).getTime();
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (ambiguousYear[0]) {
if (parsedDate.before(defaultCenturyStart)) {
parsedDate = calb.addYear(100).establish(calendar).getTime();
}
}
}
// An IllegalArgumentException will be thrown by Calendar.getTime()
// if any fields are out of range, e.g., MONTH == 17.
catch (IllegalArgumentException e) {
pos.errorIndex = start;
pos.index = oldStart;
return null;
}
return parsedDate;
}由源碼可知,最后是調用**parsedDate = calb.establish(calendar).getTime();**獲取返回值。方法的參數是calendar,calendar可以被多個線程訪問到,存在線程不安全問題。
我們再來看看**calb.establish(calendar)**的源碼

calb.establish(calendar)方法先后調用了cal.clear()和cal.set(),先清理值,再設值。但是這兩個操作并不是原子性的,也沒有線程安全機制來保證,導致多線程并發時,可能會引起cal的值出現問題了。
public class SimpleDateFormatDemoTest {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}
}
}
}
出現了兩次false,說明線程是不安全的。而且還拋異常,這個就嚴重了。
就是要使用SimpleDateFormat對象進行format或parse時,再定義為局部變量。就能保證線程安全。
public class SimpleDateFormatDemoTest1 {
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}
}
}
}
由圖可知,已經保證了線程安全,但這種方案不建議在高并發場景下使用,因為會創建大量的SimpleDateFormat對象,影響性能。
SimpleDateFormat對象還是定義為全局變量,然后需要調用SimpleDateFormat進行格式化時間時,再用synchronized保證線程安全。
public class SimpleDateFormatDemoTest2 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
synchronized (simpleDateFormat){
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
}
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}
}
}
}
如圖所示,線程是安全的。定義了全局變量SimpleDateFormat,減少了創建大量SimpleDateFormat對象的損耗。但是使用synchronized鎖,
同一時刻只有一個線程能執行鎖住的代碼塊,在高并發的情況下會影響性能。但這種方案不建議在高并發場景下使用
加Lock鎖和synchronized鎖原理是一樣的,都是使用鎖機制保證線程的安全。
public class SimpleDateFormatDemoTest3 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
lock.lock();
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}finally {
lock.unlock();
}
}
}
}
由結果可知,加Lock鎖也能保證線程安全。要注意的是,最后一定要釋放鎖,代碼里在finally里增加了lock.unlock();,保證釋放鎖。
在高并發的情況下會影響性能。這種方案不建議在高并發場景下使用
使用ThreadLocal保證每一個線程有SimpleDateFormat對象副本。這樣就能保證線程的安全。
public class SimpleDateFormatDemoTest4 {
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = threadLocal.get().format(new Date());
Date parseDate = threadLocal.get().parse(dateString);
String dateString2 = threadLocal.get().format(parseDate);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}finally {
//避免內存泄漏,使用完threadLocal后要調用remove方法清除數據
threadLocal.remove();
}
}
}
}
使用ThreadLocal能保證線程安全,且效率也是挺高的。適合高并發場景使用。
使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)
DateTimeFormatter介紹 傳送門:萬字博文教你搞懂java源碼的日期和時間相關用法
public class DateTimeFormatterDemoTest5 {
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = dateTimeFormatter.format(LocalDateTime.now());
TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);
String dateString2 = dateTimeFormatter.format(temporalAccessor);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}
}
}
}
使用DateTimeFormatter能保證線程安全,且效率也是挺高的。適合高并發場景使用。
使用FastDateFormat 替換SimpleDateFormat(FastDateFormat 是線程安全的,Apache Commons Lang包支持,不受限于java版本)
public class DateTimeFormatterDemoTest5 {
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、為線程池分配任務
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、關閉線程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = dateTimeFormatter.format(LocalDateTime.now());
TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);
String dateString2 = dateTimeFormatter.format(temporalAccessor);
System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
}
}
}
}使用FastDateFormat能保證線程安全,且效率也是挺高的。適合高并發場景使用。
Apache Commons Lang 3.5
//FastDateFormat
@Overridepublic String format(final Date date) {
return printer.format(date);
}
@Override public String format(final Date date)
{
final Calendar c = Calendar.getInstance(timeZone, locale);
c.setTime(date);
return applyRulesToString(c);
}源碼中 Calender 是在 format 方法里創建的,肯定不會出現 setTime 的線程安全問題。這樣線程安全疑惑解決了。那還有性能問題要考慮?
我們來看下FastDateFormat是怎么獲取的
FastDateFormat.getInstance();FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);
看下對應的源碼
/**
* 獲得 FastDateFormat實例,使用默認格式和地區 *
* @return FastDateFormat
*/
public static FastDateFormat getInstance() {
return CACHE.getInstance();
}
/**
* 獲得 FastDateFormat 實例,使用默認地區
* 支持緩存 *
* @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式
* @return FastDateFormat
* @throws IllegalArgumentException 日期格式問題
*/
public static FastDateFormat getInstance(final String pattern) {
return CACHE.getInstance(pattern, null, null);
}這里有用到一個CACHE,看來用了緩存,往下看
private static final FormatCache < FastDateFormat > CACHE = new FormatCache < FastDateFormat > ()
{
@Override protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
return new FastDateFormat(pattern, timeZone, locale);
}
};
//abstract class FormatCache<F extends Format>
{
... private final ConcurrentMap < Tuple, F > cInstanceCache = new ConcurrentHashMap <> (7);
private static final ConcurrentMap < Tuple, String > C_DATE_TIME_INSTANCE_CACHE = new ConcurrentHashMap <> (7);
...
}
在getInstance 方法中加了ConcurrentMap 做緩存,提高了性能。且我們知道ConcurrentMap 也是線程安全的。
/**
* 年月格式 {@link FastDateFormat}:yyyy-MM
*/
public static final FastDateFormat NORM_MONTH_FORMAT = FastDateFormat.getInstance(NORM_MONTH_PATTERN);
//FastDateFormat
public static FastDateFormat getInstance(final String pattern) {
return CACHE.getInstance(pattern, null, null);
}

如圖可證,是使用了ConcurrentMap 做緩存。且key值是格式,時區和locale(語境)三者都相同為相同的key。
以上是“java的SimpleDateFormat線程不安全怎么辦”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。