CS351 Spring 2004 Lab 12

Synchronization, Notification, and Processes


Review

ThreadControlDemo

Pausing/Stepping a Thread

What synchronizes on what

Wait and Notify, the Gritty Details

Each object in Java maintains a list of threads which are waiting on that object. For a thread to add itself to this list (and thus enter the waiting state), we must acquire the lock on that object, and then call .wait() on it:
	synchronized(foo) {
		foo.wait();
	}
The lock on the object is released atomically with the wait. The thread is then paused until it is either notify'd or interrupted.

There is a method: Thread.interrupt(), which will cause a thread to stop waiting/sleeping/blocking on interruptable I/O. This cause the thread it is called upon to wake up and an InterruptedException to be thrown.

Other than interrupt, the other way to wake up a thread is by calling the notify method on the object is waiting on. The tricky bit is what notify does (from Javadocs):

If any threads are waiting on this object, one of them is chosen to be awakened. The choice
is arbitrary and occurs at the discretion of the implementation.
So if multiple threads are waiting on one objects, the only wait to be sure the one you want is notified is to use notifyAll(). This is one of the reasons why we never assume we are being notified for the right reason.

Note as with the wait() call, the thread making the notify call must also hold the lock on the object in question. The notified thread won't proceed until the notifying thread relinquishes the lock.

Processes

Not surprisingly a processes in Java are represented by the class Process. The Process class has a selection of exec methods which allow you to execute another process. These are static methods which return the process object. From this object we can use getFooStream to get the stdout, stderr, and stdin of the process we create. This allows a Java program is communicate via pipes with the process that started it.

There is a method Process.waitFor() which will cause the current thread to wait for the process to complete (returning its exit code). If you don't use this method, the process will run in the background. (Insert story about why this is important here).

Exercise

As announced in class.

For Monday, Due Wednesday 5PM
For Wednesday, Due Friday 5PM