The order is important for the case when the buffer is full. empty.acquire()
has the effect of blocking the thread until there is at least one free slot in the buffer before attempting to add an item to the buffer.
If reversed, the function would look like:
public void insert(Object item) {
mutex.acquire();
empty.acquire();
...
If this method is called when the buffer is full, mutex
will be acquired while the thread is blocked on empty.acquire()
. Then, if another thread calls remove()
to free up a buffer slot, it will block on mutex.acquire()
. Now, no new element can be added, because the buffer is full and all attempts to remove an object will block.