mayooran February 2016

Why is the thread in the "start" method been put to wait in the below context?

I was going through an Apache Procrun tutorial and came across the following implementation for the start and stop methods of the service.

public static void start(String[] args) {
startThread();
synchronized (loggerThread) {
  try {
    loggerThread.wait();
  } catch (InterruptedException e) {
    log("'Wait' interrupted: " + e.getMessage());
  }
}
}

public static void stop(String[] args) {
if (loggerThread != null) {
  log("Stopping the thread");
  loggerThread.interrupt();
  synchronized (loggerThread) {
    loggerThread.notify();
  }
} else {
  log("No thread to interrupt");
}
}

private static void startThread() {
log("Starting the thread");
loggerThread = new Thread(new RandomLoggerService());
loggerThread.start();
}

When the start method is called, it calls the "startThread" method which will create a new thread and whatever is in its "run" method implementation would start executing. But why is the "loggerThread" synchronized on and why is it put to wait? And when I call the stop method it should notify the wait in start method right. So why is the execution logic handed over to start method again by the stop method? This is a little confusing, Please advice.

Answers


Xerillio February 2016

If we have a thread T1 that calls start() it will create a thread T2 and start it through startThread(). T1 now takes the lock/monitor on the loggerThread object and calls wait() on it. This will make T1 "pause" and wait for any notifies on the monitor for loggerThread. If another thread (T2 or any other) calls loggerThread.notify() it will wake up T1 again so it can continue.

So, to be clear, T1 is not controlling what is happening with T2, it's more the other way around. This however is something you should rarely be touching as synchronization can be done in much better (and clearer) ways.

Post Status

Asked in February 2016
Viewed 2,459 times
Voted 12
Answered 1 times

Search




Leave an answer