Use ConcurrentLinkedDeque to avoid NonSuchElementException… here is a solution to the problem.
Use ConcurrentLinkedDeque to avoid NonSuchElementException
Building a multithreaded program I ran into a problem:
ConcurrentLinkedDeque’s remove method is called by two threads and throws an exception. I can fix the problem by synchronizing this method the way I did in this code, but I’m looking for a solution without synchronization.
I searched for other suitable structures but didn’t find any that wouldn’t throw an exception or wait for the queue to be filled again.
public void releaseVehicle(DeliveryVehicle vehicle) {
acquireTable.put(vehicle.getLicense(), true);
synchronized (futureQueue) {
if (!futureQueue.isEmpty())
futureQueue.remove().resolve(vehicle);
}
}
I’m curious, is there another way?
Solution
You can use poll
instead. Since ConcurrentLinkedDeque
does not allow null elements, poll
returning null
means that the double-ended queue is empty (on call).
SomeClass element;
while ((element = deque.poll()) != null) {
do something with element
}