java-ConcurrentHashMap中基于番石榴的信号量与信号量

我的应用程序中需要一个基于密钥的Semaphore机制,偶然发现Guava是Striped.semaphore(int, int).但是,它的行为不符合预期.

使用以下代码,提取有时会返回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;
}

我在这里想念什么?谢谢

解决方法:

Guava的Striped指定多个键可能潜在地映射到相同的信号量.从Javadoc:

The guarantee provided by this class is that equal keys lead to the same lock (or semaphore), i.e. if (key1.equals(key2)) then striped.get(key1) == striped.get(key2) (assuming Object.hashCode() is correctly implemented for the keys). Note that if key1 is not equal to key2, it is not guaranteed that striped.get(key1) != striped.get(key2); the elements might nevertheless be mapped to the same lock. The lower the number of stripes, the higher the probability of this happening.

代码中的基本假设似乎是,如果与特定对象关联的信号量具有许可,则该对象在映射中具有一个条目,但事实并非如此-如果映射中存在另一个对象的条目碰巧与同一个信号量相关联,那么该许可可能由对完全不同的对象的访存获取,而该对象实际上在映射中没有任何条目.

上一篇:Semaphore源码解读


下一篇:如何正确使用PHP5信号灯?