源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java ThreadLocal 线程安全问题解决方案

  • 时间:2020-01-19 15:13 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java ThreadLocal 线程安全问题解决方案
[b]一、线程安全问题产生的原因[/b] 线程安全问题都是由全局变量及静态变量引起的 [b]二、线程安全问题[/b] SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf内有一个对Caleadar对象的引用,在源码sdf.parse(dateStr);源码中calendar.clear();和calendar.getTime(); // 获取calendar的时间 [img]http://files.jb51.net/file_images/article/201609/2016930143401245.png?2016830143415[/img] 如果 线程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);
  } 
}
[b]使用synchronized解决方案:[/b]
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);
    }
  }
}

感谢阅读本文,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部