Usecase:
1.Have a queue which is getting filled asynchronously from another source.
2.Need to consume the data from that queue one after another. There is a usecase(play a sound) for which data extraction from the queue should happen in every X sec when there are multiple elements in queue.
Below is a sample code snippet for that:
Queue<Wrapper> q = new ConcurrentLinkedQueue<>();
// filling up queue
void add(A obj) {
synchronized (q) {
q.add(obj);
q.notify();
}
}
Below is the consumer code for extracting the data:
class Consumer extends Thread {
@Override
public void run() {
while ( true ) {
try {
synchronized ( q ) {
while ( q.isEmpty() )
q.wait();
// Get the item off of the queue
A w = q.remove();
// Process the work item
playSomeSoundForXsec(w);
Thread.sleep(3000);
}
}
catch ( InterruptedException ie ) {
break;
}
}
}
}
Issues with the above code:
Static code analysis error: "
wait(..)
should be used instead of "Thread.sleep(..)
" when a lock is heldWhen continuous events are getting filled to the queue, sound stops coming out.
what will be better way to handle the above usecase.