在线程中同步哈希映射



我在同步idMap时遇到了一些问题。此映射用于同时运行的两种run()方法。在第一个 run() 方法中,我只是将事件 id 值)映射到响应 id(键)。在第二个 run() 方法中,我希望获得具有相同响应 ID(键)的事件 ID(值)。但是,有时存在某些事件 ID,有时无法获取它们。该程序编译得很好,但我不是线程专家,我相信线程导致这个idMap不同步。我的问题很简单,如何才能使idMap顺利工作并按预期获取事件 ID?

ConcurrentHashMap<String, String> idMap = new ConcurrentHashMap<String, String>();
ConcurrentHashMap<String, ExecutorService> executors = new ConcurrentHashMap<String, ExecutorService>();
private final class ResponderTask implements Runnable {
    private ResponderTask(Event event) {
        this.event = event;
    }
    // 1st run()    
    public void run() {
        idMap.put(response.getId(), event.getId()); 
    }
}//end ResponderTask 
private final class QuoteTask implements Runnable {
    //constructor
    //2nd run() 
    public void run() {
        IdMap.get(response.getId());
    }
}//end QuoteTask
public void onResponse(final Response response) {
    ExecutorService quoteExecutor = executors.get(response.getId());
    if (quoteExecutor == null) {
        quoteExecutor = Executors.newSingleThreadExecutor();                
        executors.put(event.getId(), quoteExecutor);            
    }
    quoteExecutor.execute(new ResponderTask(event));
}

但是,有时存在某些事件 ID,有时无法获取它们。该程序编译得很好,但我不是线程专家,我相信线程导致此idMap不同步。

idMap是一个正确同步并被许多人高度使用和测试的ConcurrentHashMap。 如果查找时 id 不在地图中,则它尚未放入其中。 如果你对你的代码有更多的解释,我们也许能够找到你的问题。

例如,我看不到response对象来自哪里。 ResponseTask是否有可能正在处理与您预期的不同的响应? responseevent应该是同一个论点吗?

我的问题很简单,如何使idMap顺利工作并按预期获取事件ID?

弄清楚程序的正确操作应该是什么有点困难。 如果您正在寻找另一个线程来获取事件,您可以使用BlockingQueue。 然后,您的另一个线程可以执行一个queue.take()该将等待,直到有事件要处理。 但我不确定这里的目标是什么。

非常奇怪的一件事是使用ExecutorService地图。 你真的需要其中的多个吗? 我怀疑你真的应该使用一个Executors.newCachedThreadPool(). 但是,也许您希望单个线程处理具有相同 id 的所有请求,在这种情况下,您的代码应该可以工作。 我假设当您要关闭应用程序时,您正在执行类似以下操作的操作:

for (ExecutorService executor : executors.values()) {
    executor.shutdown();
}

最新更新