the title already says it all, in my code I have an object that implements a Linked Blocking Queue and offers methods of inserting and obtaining an element in the queue, I would like the insertion / extraction from the queue to take place in a LIFO way and not in a FIFO way , is there any way to do it?
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Usr {
private BlockingQueue<String> requestsQueue = new LinkedBlockingQueue<String>();
public Usr() {
}
public void insertRequest(String username) {
try {
this.requestsQueue.put(username);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getRequest() {
try {
return this.requestsQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
Just replace your LinkedBlockingQueue
with LinkedBlockingDeque
and use takeLast()
instead of take()
.
Deque is a collection that supports element insertion and removal at both ends. See details here: https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingDeque.html
Cheers!