gpt4 book ai didi

java - 缓存资源的线程安全更新

转载 作者:行者123 更新时间:2023-12-01 04:27:04 26 4
gpt4 key购买 nike

逻辑非常简单:

Foo foo = cache.get();
if (isUpToDate(foo)) {
return foo;
} else {
foo = getUpdatedFoo(); // slow or expensive
cache.put(foo);
return foo;
}

但是,我想确认一下

  1. 一次只有一个线程调用 getUpdatedFoo()
  2. 如果线程 A 已在调用 getUpdatedFoo(),则线程 B 不会调用它,而不只是等待线程 A 的结果

我可能可以根据 JCiP 的 Memoizer 模式拼凑一些东西,但我怀疑有一种更简单的方法——可能使用 Guava CacheBuilder?不过,目前还不清楚如何实现。

<小时/>

更新:按照FrankPL's answer实现了双重检查锁定模式如下:

Foo foo = cache.get();
if (!isUpToDate(foo)) {
lock.lock(); // Will block if some other thread is refreshing
try {
// See if some other thread already refreshed for us
foo = cache.get();
if (!isUpToDate(foo)) {
// guess not, we'll refresh it ourselves
foo = getUpdatedFoo();
cache.put(foo);
}
} finally {
lock.unlock();
}
}
return foo;

最佳答案

参见http://en.wikipedia.org/wiki/Double-checked_locking了解您可以使用的双重检查锁定模式。使用 getUpdatedFoo(),而不是代码示例中使用的 new Helper()

关于java - 缓存资源的线程安全更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18411474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com