Java ThreadLocal 安全執行緒問題解決方案_java

來源:互聯網
上載者:User

一、安全執行緒問題產生的原因

安全執行緒問題都是由全域變數及靜態變數引起的

二、安全執行緒問題

SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf內有一個對Caleadar對象的引用,在源碼sdf.parse(dateStr);源碼中calendar.clear();和calendar.getTime(); // 擷取calendar的時間

如果 線程A 調用了 sdf.parse(), 並且進行了 calendar.clear()後還未執行calendar.getTime()的時候,線程B又調用了sdf.parse(), 這時候線程B也執行了sdf.clear()方法, 這樣就導致線程A的的calendar資料被清空了;

ThreadLocal是使用空間換時間,synchronized是使用時間換空間

使用ThreadLocal解決安全執行緒:

public class ThreadLocalDateUtil {  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);  } }

使用synchronized解決方案:

public class DateSyncUtil {  private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      public static String formatDate(Date date)throws ParseException{    synchronized(sdf){      return sdf.format(date);    }   }     public static Date parse(String strDate) throws ParseException{    synchronized(sdf){      return sdf.parse(strDate);    }  }}

感謝閱讀本文,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.