I have two threads, a consumer and a producer. The consumer thread is the main thread while the producer thread is created by a third party library I use.
You make a request for a List of data to the producer thread using ProducerChannel‘s requestData(), which returns immediately. Then, the producer thread will generate data one by one asynchronously and uses a call back method to send each of them. I want the method that requests data to return the result synchronously. The most straightforward way would be to use wait() and notify() like below.
public class DataFeed {
boolean done;
private List<Data> dataList;
private ProducerChannel producerChannel;
// This method should be synchronous.
public List<Data> getDataList() {
this.producerChannel.requestData();
while (!done) {
wait();
}
List<Data> dataList = this.dataList;
this.dataList = null;
return dataList;
}
// This is the call back method invoked by the producer thread.
public void generated(Data data) {
if (data == null) {
done = true; // End of data.
notify();
}
else {
this.dataList.add(data);
}
}
}
Note that there’s only one consumer thread in the entire application. That’s why DataFeed has only one List to hold the result for each request. I learned that the Executor framework is now the preferred way to manage threads. How can I refactor this class so that it does not use Thread objects explicitly while not creating additional threads?
I’m the OP. While BlockingQueue would certainly work, I learned that Semaphore would be a simpler solution.