Max Max - 1 month ago 14
Java Question

Java concurrency in practice - Listing 14.9 explanation?

Few listings from JCIP already appeared here. Here is one more (orig. code):

public class ThreadGate {
private boolean isOpen;
private int generation;

public synchronized void close() {
isOpen = false;
}

public synchronized void open() {
++generation;
isOpen = true;
notifyAll();
}

public synchronized void await() throws InterruptedException {
int arrivalGeneration = generation;
while (!isOpen && arrivalGeneration == generation) {
wait();
}
}
}


Comment in book:

The condition predicate used by await is more complicated than simply testing isOpen. This is needed because if N threads are waiting at the gate at the time it is opened, they should all be allowed to proceed. But, if the gate is opened and closed in rapid succession, all threads might not be released if await examines only isOpen: by the time all the threads receive the notification, reacquire the lock, and emerge from wait, the gate may have closed again. So ThreadGate uses a somewhat more complicated condition predicate: every time the gate is closed, a "generation" counter is incremented, and a thread may pass await if the gate is open now or if the gate has opened since this thread arrived at the gate.


Guys, you may laugh, but I can't get it :). Questions:


  1. explain usage of
    arrivalGeneration == generation
    to me in terms of thread T1, T2,... and execution flow.

  2. why passage says
    every time the gate is closed, a generation counter is incremented
    ? How it happens?



Thanks to everybody!

Max Max
Answer

For those, who are interested, seek for answer here.

In this listing the waiting thread T1 is interested if any open event happened during the wait (we do not care whether any close events happened), generation counter helps us to find out this fact.