はコードです:私たちは、単に数を取得するためにqueue.size()
を使用できるようこのコードでは、Collection.size()を使用してカウンタを置き換えることはできますか?ここ
public class LogService {
private final BlockingQueue<String> queue;
private final LoggerThread loggerThread;
private final PrintWriter writer;
@GuardedBy("this") private boolean isShutdown;
@GuardedBy("this") private int reservations; // <-- counter
public void start() { loggerThread.start(); }
public void stop() {
synchronized (this) { isShutdown = true; }
loggerThread.interrupt();
}
public void log(String msg) throws InterruptedException {
synchronized (this) {
if (isShutdown)
throw new IllegalStateException(...);
++reservations;
}
queue.put(msg);
}
private class LoggerThread extends Thread {
public void run() {
try {
while (true) {
try {
synchronized (LogService.this) {
if (isShutdown && reservations == 0)
break;
}
String msg = queue.take();
synchronized (LogService.this) {
--reservations;
}
writer.println(msg);
} catch (InterruptedException e) { /* retry */ }
}
} finally {
writer.close();
}
}
}
}
それが本の練習でのJava並行処理からの抜粋だ、と私はそれについて考えているかもしれないカウンターreservations
は不要ですqueue
の要素。
私は正しいですか?
キュー 'put'と' get'は同期していません。 '予約'が変更されました。 –