When using BlockingQueue to consume data that is produced what is the most efficient method for waiting for the data to appear?
Scenario:
Step 1) The data list will be a data store where timestamps are added to. These timestamps are required to be ordered by closest to current time priority. This list may be empty. A thread will be inserting the timestamps into it. Produce
Step 2) I want to consume the data in here in another thread that will take the timestamps from data and check if they are after the current time. Consumer then Produce
Step 3) If they are after the current time then send them on to another thread to be consumed and processed. Once the time stamp data is processed here, remove from the Step 1 data store. Consume then edit the original list.
In the below code the data field refers to the data store in step 1. The results is the list of timestamps that have been sent that are after the current time. Step 2. The results will then be consumed step 3.
private BlockingQueue<LocalTime> data;
private final LinkedBlockingQueue<Result> results = new LinkedBlockingQueue<Result>();
@Override
public void run() {
while (!data.isEmpty()) {
for (LocalTime dataTime : data) {
if (new LocalTime().isAfter(dataTime)) {
results.put(result);
}
}
}
}
Questions What is the most efficient way to wait for data to be added in the data list that could be potentially empty? Focus on:
while (!data.isEmpty())
Following from an earlier question.
data.take()!=null
. TheisEmpty
call is non-blocking. – Separatrix!data.isEmpty()
which means you are looping till there is some data in your data list (waiting for data to be consumed). But your requirement says - "wait for data to be added in the data list that could be potentially empty." What is your requirement here? – Paviorresults.put(result);
?? I think this would be the very initial case. What will happen once some data is produced. As per step3, you want it to be consumed by some thread, and lets say 1 data is produced, and it is consumed, now again same thread would be waiting for next item to be produced? Key thing is - is it the same thread or different thread which would wait for data to be produced fromresults.put(result);
OR thread will keep on consuming, but if data is not there then it should wait? Single or multi thread part is not clear. – Pavior