Work with BlockingQueue in Java

Unbounded Queue

BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>();

Bounded Queue

BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>(10);

Adding Elements

  • add() – returns true if insertion was successful, otherwise throws an IllegalStateException
  • put() – inserts the specified element into a queue, waiting for a free slot if necessary
  • offer() – returns true if insertion was successful, otherwise false
  • offer(E e, long timeout, TimeUnit unit) – tries to insert element into a queue and waits for an available slot within a specified timeout

Retrieving Elements

  • take() – waits for a head element of a queue and removes it. If the queue is empty, it blocks and waits for an element to become available
  • poll(long timeout, TimeUnit unit) – retrieves and removes the head of the queue, waiting up to the specified wait time if necessary for an element to become available. Returns null after a timeout

References
http://www.baeldung.com/java-blocking-queue
https://pupli.net/2017/07/24/remote-procedure-call-rpc-sample-in-rabbitmq/