在后台android中更新时,从concurrentHashMap访问数据

时间:2015-02-14 15:45:47

标签: android hashmap java.util.concurrent concurrenthashmap

我有一个静态的concurrentHashMap对象,它已在后台更新。当它正在更新时,我想在另一个线程中访问它的值。我正在使用concurrentHashMap,我从文档中了解到它并认为它适合这种情况

这就是我正在做的事情

for (Map.Entry<String, ArrayList<property>> entry : alldata.entrySet())
        {
            udata.put(entry.getKey(), new ArrayList<property>(entry.getValue()));
        }

在上面的代码我正在更新udata从服务器获取数据但在后台。

在另一个线程中,我正在访问它的一些信息..

  for (String s: sTypes) 
        {
                    if(jprocess.udata != null)
                        {
                            if (jprocess.udata.get(s) != null)
                                {
                                    if (jprocess.udata.get(s).size() > 0) {
                                        if (xcor < jprocess.udata.get(s).size())
                                            if (xcor != -1) {
                                                allData.add(jprocess.udata.get(s).get(xcor));
                                            }
                                    }
                                }
                        }
                }

但当我尝试从中访问任何索引时,我无法访问任何内容,我希望它很清楚我想要的内容。

我已经尝试过ConcurrentHashMap,这应该适用于这种情况,但可能是我不太了解..

1 个答案:

答案 0 :(得分:1)

如果您正在使用ConcurrentHashMap,那么就没有意义它将无法工作。我强烈怀疑您是在尝试访问错误的索引,或者在插入和访问特定索引之间没有同步。

为此,只需在代码和每个if条件中检查udata的大小和xcor的值。

此外,请仔细阅读this,并确信您将确信ConcurrentHashMap是您问题的正确解决方案。