printable version

Test 1 Review B

[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Problem R1b.1.

In an earlier question, we implemented a ThreadHolder class, where threads could call the awaitRelease method to stall until another thread calls release with a number saying how many threads stuck in awaitRelease should be released. (You should assume that release is only called when there are enough threads stalling that all can be released immediately.)

public class ThreadHolder {
    private int released = 0;
    private Object lock = new Object();

    public void awaitRelease() {
        synchronized (lock) {
            while (released <= 0) {
                try { lock.wait(); } catch (InterruptedException e) {}
            }
            --released;
        }
    }

    public void release(int n) {
        synchronized (lock) {
            released += n;
            lock.notifyAll();
        }
    }
}

This solution, though, is prone to starvation even if a thread regularly calls release with a positive parameter n. Explain how starvation may occur, and repair the code so starvation will not occur.