有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在静态final字段中保存线程本地值是一种糟糕的做法吗?

我在遗留系统中遇到了以下代码

private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal(){

    @Override
    protected Object initialValue() {
        //Set initial value
        return new SimpleDateFormat("");
    }
};


private static final DateFormat someValue = dateFormatThreadLocal.get();

然而,我有以下问题

1.)将线程局部变量定义为final是个好主意吗。(我知道静电很好)

2.)保持线程本地是个好主意吗。在静态(或静态和最终)实例变量中进行get()调用?(如果我们这样做,它不会妨碍线程本地化的全部目的吗)


共 (1) 个答案

  1. # 1 楼答案

    1.) Is it a good idea to define thread locals as final. ( I know static is fine)

    如果您没有分配给dateFormatThreadLocal,那么final没有任何区别。然而,这通常是一个好主意,因为它可以防止您意外地分配给它

    2.) Is it a good idea to hold thread local.get() call in a static (or both static and final) instance variable? ( if we do this doesn't it hinder the whole purpose of having thread-local at first place )

    不,不是。实际上,如果你这样做那么它首先就破坏了线程本地化的全部目的

    无论哪个线程首先加载该类,都将检索其SimpleDataFormat,并将对该对象的引用存储在someValue中。然后,无论何时使用someValue,当前线程都将使用该线程的SimpleDataFormat(它之前得到的),而不是调用dateFormatThreadLocal.get()并获得自己的

    如果您使用的是ThreadLocal,那么您大概不希望每个线程都使用同一个对象,否则为什么还要麻烦使用它呢