乱数をリッスンするプログラムがあります。それは私に番号と新しいカウントを与えるパブリッシャーに接続されており、更新を取得するたびに、その番号の現在のカウントを HashMap に保存しています。
リクエストをリッスンするSSLサーバーもあります。「7 はいくつありますか」という要求があった場合、私は HashMap で値を返すだけです。
ここで、その数が 0 回発生した場合は、1 回発生するまで待機し、その時点でのカウントを返すというロジックを追加します。ただし、Thread の run メソッドの制限により、無効でなければならないという問題が発生しています。とにかく、メソッドを常に新しいスレッドを起動するものとして宣言するだけなのか、それとも私がやっていることよりもそれを処理するためのより良い方法があるのだろうか。ここに私が持っているものがあります:
private static volatile HashMap<Integer, Integer> occurenceMap= new HashMap<Integer, Integer>();
public synchronized static int getNumOccurrences(final Integer number) {
try {
(new Thread() {
public void run() {
Integer occurrences = occurenceMap.get(number);
if ( occurrences != null && occurrences > 0 ) {
// here I would like to just return occurences;
} else {
CountDownLatch latch = new CountDownLatch(1);
pendingList.put(number, latch);
latch.await();
// elsewhere in the code, I call countdown when I get a hit
pendingList.remove(number);
// once we've counted down, I would like to return the value
}
}
}).start();
} catch ( Throwable t ) { }
}
ただし、run メソッドに return ステートメントを入れることはできません。では、これはどのように行うのが最善でしょうか?
ありがとうございました!