【发布时间】:2020-01-22 07:13:13
【问题描述】:
有时在 java 中我有线程不安全且创建成本高的对象。我想为这些对象创建一个缓存,因此我不需要重新创建它们,但它还必须防止对同一对象的并发访问。
例如,我可能有DateFormat,创建它的成本太高,但我不能共享一个DateFormat。为了争论,假设我不能使用线程安全的DateFormat。
如果能够像这样创建一些缓存,那就太棒了:
Cache<DateFormat> cache = new Cache(() -> dateFormatCreator());
// and now make use of a dateFormat that might be created for this call
// or it might be an existing one from the cache.
cache.withExclusiveAccessToObject(dateFormat -> {
// use the dateFormat here, it is not in use by any other thread at the same time.
// new dateFormats can be created on the fly as needed.
});
我还应该提到ThreadLocal 并不理想,因为我无法确保线程会被重用。
【问题讨论】:
-
有问题吗? / 对于一个小对象,您可以只使用
ThreadLocal(这对它们来说是唯一的好用处)。 -
不错的@BenManes 现在我被宠坏了。