【问题标题】:Do I need to call ThreadLocal.remove in the following case在以下情况下是否需要调用 ThreadLocal.remove
【发布时间】:2010-08-22 06:06:43
【问题描述】:

而不是写下面的非线程安全方法。

private static final Calendar calendar = Calendar.getInstance();
public void fun() {
    // Going to call mutable methods in calendar.
}

我将其更改为线程安全版本。

public void fun() {
    final Calendar calendar = Calendar.getInstance();
    // Going to call mutable methods in calendar.
}

我没有每次都为同一个线程创建一个新实例,而是通过

public void fun() {
    final Calendar calendar = getCalendar();
    // Going to call mutable methods in calendar.
}

/**
 * Returns thread safe calendar.
 * @return thread safe calendar
 */
public Calendar getCalendar() {
    return calendar.get();
}

private static final ThreadLocal <Calendar> calendar = new ThreadLocal <Calendar>() {
    @Override protected Calendar initialValue() {
        return Calendar.getInstance();
     }
 };

对于我的第三种方法,是否需要致电ThreadLocal.remove

【问题讨论】:

    标签: java concurrency thread-local


    【解决方案1】:

    如果您的唯一目的是使其线程安全,那么确实没有必要这样做。但是当线程由线程池维护并且您的意图更多是为线程池中每个新释放的线程赋予其自己的初始值时,那么您应该这样做。

    【讨论】:

      【解决方案2】:

      正如@BalusC 所说,这取决于您关心的问题。

      我怀疑您使用本地线程回收Calendar 对象实际上可能比不调用Calendar.getInstance() 节省的成本更多。这有点过早的微优化的味道。

      【讨论】:

      • 但是,Joshua Bloch 甚至建议将 ThreadLocal 用于 SimpleDateFormat 示例。 (我打算用于 Calendar、SimpleDateFormat 和 NumberFormat) - old.nabble.com/…
      • 但是什么都没有!优化规则 #1 - 首先分析您的应用程序。
      • @Yan Cheng Calendar 应该是一个相当便宜的构造对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多