Ecco il codice:Posso usare Collection.size() per sostituire il contatore in questo codice?
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();
}
}
}
}
Si tratta di un frammento dal libro Java Concurrency in Practice, e sto pensando di che forse il contatore reservations
è inutile come abbiamo potuto usare semplicemente queue.size()
per ottenere il numero di elementi in queue
.
Ho ragione?
coda 'put' e' get' non sono sincronizzati. la modifica 'prenotazioni' è. –