In Listing 7.15 of "Concurrency in Practice", can both internal and external classes synchronize to "this"?

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;
  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 (this) {
                          if (isShutdown && reservations == 0)
                              break;
                      }
                      String msg = queue.take();
                      synchronized (this) { --reservations; }
                      writer.println(msg);
                  } catch (InterruptedException e) { /* retry */ }
              }
          } finally {
              writer.close();
          }
      }
  }
}

This is a list of 7.15 from the book "Java Concurrency In Practice". I can’t understand how synchronization can work there. Why are the inner and outer classes synchronized on different objects for access fields? Should this error and inner class use synchronization (LogService.this)? Or am I completely misunderstanding how synchronization works?

+4
source share
1 answer

This is a mistake in the book, given in the mistake

p.154: 7.15 () (LogService.this).

+3

All Articles