1

私は HashMap を持っています。そのタイプは、HashMap<String,HashMap<String,int>>この HashMap を反復処理し、任意のキーの値が 0 である内側の HashMap を削除する必要があります。

このような削除によって内側の HashMap が空になる場合、内側の HashMap の対応するキーが外側の HashMap から削除されます。それを繰り返してから、要件に一致する要素を削除しようとしましたが、ConcurrentModificationException.

次のコードを試しました:

synchronized(MyConstants.cliListUpdateList)
{
    synchronized(MyConstants.cliList)
    {
        outerEntries = MyConstants.cliListUpdateList.entrySet();
        outerIterator = outerEntries.iterator();

        while(outerIterator.hasNext())
        {
            outerEnt = (Entry) outerIterator.next();
            innerHashMap = (HashMap) outerEnt.getValue();
            synchronized(innerHashMap)
            {//synchronize innerhashmap
            innerEntries = innerHashMap.entrySet();
            innerIterator = innerEntries.iterator();
            synchronized(innerIterator)
            {
            while(innerIterator.hasNext())
            {
                innerEnt = (Entry) innerIterator.next();
                int k = Integer.parseInt((String)innerEnt.getValue());
                if(k==0)
                {
                    innerHashMap.remove(innerEnt.getKey());
                    if(innerHashMap.isEmpty())
                    {
                        MyConstants.cliListUpdateList.remove(outerEnt.getKey());
                    }

                    ArrayList ports = (ArrayList) MyConstants.cliList.get(outerEnt.getKey());
                    ports.remove((String)innerEnt.getKey());
                    if(ports.isEmpty())
                    {
                        MyConstants.cliList.remove(outerEnt.getKey());
                    }
                }
                else
                {
                    k--;
                    innerHashMap.put(innerEnt.getKey(), k+"");
                    MyConstants.cliListUpdateList.put(outerEnt.getKey(), innerHashMap);
                }

            }
            }
        }//synchronize innerhashmap
        }


        System.out.println(MyConstants.cliListUpdateList + " <---> "+ MyConstants.cliList);

    }
}

この行で例外が発生しています: innerEnt = (Entry) innerIterator.next();。Iterator クラスが提供する remove メソッドを試してみました。でもそれもダメ。

編集

Java docs から私はこれをよく知っていますif a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this(ConcurrentModificationException) exceptionが、まったく同じ機能が必要です。

4

2 に答える 2

7

問題を完全に解決できない可能性がありますが、代わりにinnerHashMap.remove(innerEnt.getKey());イテレータの remove メソッドを使用する必要がありますinnerIterator.remove();

于 2012-03-12T10:29:37.597 に答える
2

Synchronized Hashmap を使用してみましたか? Collections.synchronizedMap(new HashMap())またはConcurrentHashMapを見てください

于 2012-03-12T10:21:03.980 に答える