在静态最终字段中保存线程本地值是一种不好的做法吗?
Is it a bad practice to save thread local values in static final field?
我在遗留系统中遇到了以下代码,
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.) 将线程 local.get() 调用保存在静态(或静态和最终)实例变量中是个好主意吗? (如果我们这样做,它不会妨碍首先拥有线程本地的整个目的)
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 )
不,不是。实际上,如果你 做 这样做,那么它首先会破坏 thread-local 的全部目的。
无论哪个线程碰巧首先加载 class,都会检索其 SimpleDateFormat,并将对该对象的引用存储在 someValue
中。然后,每当您使用 someValue
时,当前线程将使用 该线程的 SimpleDateFormat(它之前获得的)而不是调用 dateFormatThreadLocal.get()
并获取它自己的。
如果您正在使用 ThreadLocal,那么您可能不希望每个线程都使用相同的对象 - 否则为什么要费心使用它?
我在遗留系统中遇到了以下代码,
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.) 将线程 local.get() 调用保存在静态(或静态和最终)实例变量中是个好主意吗? (如果我们这样做,它不会妨碍首先拥有线程本地的整个目的)
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 )
不,不是。实际上,如果你 做 这样做,那么它首先会破坏 thread-local 的全部目的。
无论哪个线程碰巧首先加载 class,都会检索其 SimpleDateFormat,并将对该对象的引用存储在 someValue
中。然后,每当您使用 someValue
时,当前线程将使用 该线程的 SimpleDateFormat(它之前获得的)而不是调用 dateFormatThreadLocal.get()
并获取它自己的。
如果您正在使用 ThreadLocal,那么您可能不希望每个线程都使用相同的对象 - 否则为什么要费心使用它?