Monday, 23 February 2009

Thinking like Eckel: Objects are Like Trains

Basics First: The wait/notify dynamic

One fine day, an instance of the java.lang.Object class had its wait() method invoked and application X came to a standstill. Why and wherefore did this happen?

void wait()

wait throws an InterruptedException. It causes the current thread to WAIT until another thread calls notify or notifyAll on the same object.

wait() == wait(0) == wait(0,0)

which means invoke wait with a zero millisecond timeout (i.e. never timeout). The current thread must own the object's monitor. Think of it as a UNIX process that sleeps until some event occurs or a bus that stops at traffic lights and must be "notified" either by the traffic lights or by a car honking from behind it! An object, to put it in baby terms, is like a "choo-choo train"! A "choo-choo" train with locks that can only be manipulated by synchronized methods! Tampering illegaly with the locks results in a vandalism-detection mechanism being triggered.

Some notes on wait/notify

There's a little more to wait/notify than meets the eye and some of this "extra insight" can be obtained from reading good Java books such as Bruce Eckel's Thinking in Java (Bruce Eckel is both a "Java Black Belt" and also founding member of the C++ Standards Committee, the two facts being not entirely unrelated). One key point he makes is that synchronized methods of an object can be called on an object in a wait state, precisely because calling wait releases the lock on the object. Because wait does jiggery-pokery with the object, calling wait outside of a synchronized method results in an IllegalMonitorStateException (present since JDK 1.0 so don't act all surprised!)

No comments:

Blog Archive