【发布时间】:2023-03-25 19:30:02
【问题描述】:
我需要在我的应用程序中使用基于密钥的 Semaphore 机制,并偶然发现了 Guava 的 Striped.semaphore(int, int)。但是,它的行为并不像预期的那样。
使用以下代码,fetch 有时会返回 null。这两种方法都由不同的线程访问。我希望调用 fetch 的线程等到地图中的 Blubb 可用。
private final Striped<Semaphore> semaphores = Striped.semaphore(64, 0);
private final Map<String, Blubb> blubbs = Collections.synchronizedMap(new HashMap<String, Blubb>());
private Semaphore getSemaphore(final String key) {
return semaphores.get(key);
}
@Override
public void put(String key, Blubb blubb) {
blubb.put(key, blubb);
final Semaphore semaphore = getSemaphore(toUser);
semaphore.release();
}
@Override
public blubb fetch(final String key) {
try {
final Semaphore semaphore = getSemaphore(key);
final boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
return blubbs.get(key);
} catch (final InterruptedException e) {
e.printStackTrace();
}
return null;
}
如果我使用以下代码切换回基本 Java,一切都会按预期工作。
private final Map<String, Semaphore> semaphoresMap = new ConcurrentHashMap<String, Semaphore>();
private Semaphore getSemaphore(final String key) {
Semaphore semaphore = semaphoresMap.get(key);
if (semaphore == null) {
semaphore = new Semaphore(0);
semaphoresMap.put(key, semaphore);
}
return semaphore;
}
我在这里缺少什么?谢谢
【问题讨论】:
标签: java concurrency guava semaphore