1

There is an ExecutorService that has 3 threads that each one add Pair<String,Integer> objects to a TreeSet<Pair<String,Integer>>. The addToSet() method is declared synchronized and everything works fine. But I must implement a new thread that execute a scheduled task that has to access this Set and print all the values. The problem is that sometimes the scheduled thread crashes(the other threads work fine). I think that it crashes because the Set is being modified by the other 3 threads during the for loop of the printer(scheduled thread).

4

2 に答える 2

1

addToSetメソッドとすべての値を出力するメソッドとの間で相互排除が必要です。それを行う1つの方法:

Object setLock = new Object(); // Put this in a scope where all threads can access it

void addToSet( T element ){
    synchronized(setLock) {
       //add it
   }
}

void printAllValues(){
   synchronized(setLock) {
       //print the values
   }
}
于 2012-10-26T12:31:41.390 に答える
0

これを実装する最も安全な方法は、同期されたコンテキストでセットの防御コピーを作成し、それを他のプロセスに使用することです。

いくつかの大まかな行で:

public void run() {
    TreeSet<...> localSet;
    synchronized (commonSet ) {
        localSet = new TreeSet(commonSet);
    }
    doStuff(localSet);
    ...
}

これは、セット内のオブジェクトへの同時アクセスを解決しないことに注意してください (それらが変更可能な場合)。

于 2012-10-26T12:32:05.497 に答える