The Monitor
class from Guava gives us a solution that allows multiple conditions and completely eliminates the possibility of notifying all threads by switching from an explicit notification system to an implicit one. Let's take a look at an example:
public class MonitorSample { private List<String> list = new ArrayList<String>(); private static final int MAX_SIZE = 10; private Monitor monitor = new Monitor(); private Monitor.Guard listBelowCapacity = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { return list.size() < MAX_SIZE; } }; public void addToList(String item) throws InterruptedException { monitor.enterWhen(listBelowCapacity); try { list.add(item); } finally { monitor.leave(); } } }
Let's go over the interesting parts of our example. First we are creating a new instance of a Monitor
class. Next we use our newly created...