我不了解DynamicVariable
背后的代码和逻辑:
首先,您创建一个具有默认值...默认值的DynamicVariable
实例???您想要每个线程一个值!这是否意味着您可能在所有线程之间共享相同的默认值?达不到目的...还是?
然后我在所有示例中都看到withValue
几乎每次都像创建一个新实例一样,还是?
例如ThreadLocal
具有合理的经典案例SimpleDateFormat
每次创建都非常昂贵,而且不是线程安全的:
import java.text.SimpleDateFormat;
static ThreadLocal<SimpleDateFormat> dateFormatTl = new ThreadLocal<SimpleDateFormat>();
...
// many threads execute this, check if there already exists a
// Thread-bound instance otherwise create a new one per-thread
if (dateFormatTl.get() == null) {
dateFormatTl.set(new SimpleDateFormat("yyyy-dd-MM HH:mm:ss"));
}
// safely use the Thread-bound instance
SimpleDateFormat dateFormat = dateFormatTl.get();
dateFormat.format(new Date(java.util.Date.getTime()));
如何在Scala中使用
DynamicVariable
复制上面的相同功能?// create with default instance ...
// what for? I don't want the same instance shared across all Threads!
val dateFormatDv = new DynamicVariable[SimpleDateFormat](new SimpleDateFormat("yyyy-dd-MM HH:mm:ss"))
// many threads execute this ...
// I see it is creating one new instance each time, and
// that is not what I want
dateFormatDv.withValue(new SimpleDateFormat("yyyy-dd-MM HH:mm:ss")) {
// safely use the Thread-bound instance, but this is a new one each time arrrggggg
dateFormatDv.value.format(new Date(java.util.Date.getTime()))
}
最佳答案
您可以按照以下步骤进行操作:
Future {
dateFormatDv.withValue(new SimpleDateFormat("yyyy-dd-MM HH:mm:ss")) {
doStuffWithDateFormat(dateFormatDv.value)
doMoreStuffWithTheSameFormatInstance(dateFormatDv.value)
}
}
Future {
dateFormatDv.withValue(new SimpleDateFormat("yyyy-dd-MM HH:mm:ss")) {
useADifferentInstanceOfDateFormat(dateFormat.value)
}
}
至于默认值,它只是让您对其进行设置,以便可以在当前线程中方便地使用它而无需
.withValue
doSomethingWithDefaultFormatInstance(dateFormat.value)