Search code examples
javaconcurrencythisinner-classes

Using this keyword as lock in concurrency


In the following program, does the this keywords in the LoggerThread class refer to LoggerThread object or LogService object? Logically it should refer to LogService in order for the syncronization to work, but semantically it seems it is referring to LoggerThread.

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();
            }
        }
    }
}

Thank you for your help


Solution

  • this within LoggerThread methods refers to a LoggerThread instance.
    LogService.this refers to the outer class.


    Both isShutdown and reservations are synchronised by the different locks (LoggerThread.this and LogService.this), so @GuardedBy("this") doesn't reflect the reality.