Java LinkedBlockingDeque Example

By Arvind Rai, November 16, 2023
On this page, I will create LinkedBlockingDeque example in Java application. LinkedBlockingDeque is introduced in Java 6. It belongs to java.util.concurrent package. LinkedBlockingDeque is a BlockingDeque which works with linked nodes.

BlockingDeque

BlockingDeque is a Deque which supports blocking operation. Deque is a queue that supports insertion and deletion at both sides. The working of BlockingDeque is that while insertion, it waits to become empty if already full and while deletion it waits to become non-empty if already empty.

LinkedBlockingDeque

LinkedBlockingDeque implements BlockingDeque. LinkedBlockingDeque works on the basis of linked nodes. It can be instantiated as unbounded as well as bounded by passing the capacity.

add(E e): Inserts the given element at the end of deque. If LinkedBlockingDeque is bounded and there is no space to add element, this method throws error.
offer(E e): It inserts the elements if there is space and returns true otherwise false.
peek(): It retrieves but does not remove the element.
poll(): Retrieves and removes the element.

Example

BlockingDequeDemo.java
package com.concretepage.concurrent;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class BlockingDequeDemo {
	static BlockingDeque<String> bd=new LinkedBlockingDeque<String>(1);
	public static void main(String[] args) {
		ExecutorService exService = Executors.newFixedThreadPool(2);
		BlockingDequeDemo bdeque = new BlockingDequeDemo();
		ElementAdd elementAdd = bdeque.new ElementAdd();
		ElementGet elementGet = bdeque.new ElementGet();
		exService.execute(elementAdd);
		exService.execute(elementGet);
		exService.shutdown();
	}
	class ElementAdd implements Runnable{
		@Override
		public void run() {
			for(;;){
				try {
					String s= bd.take();
					System.out.println("Element received is: "+s);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	class ElementGet implements Runnable {
		@Override
		public void run() {
			for(int i=0;i < 5;i++){
				try {
					bd.put("A"+i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
} 
Find the output.
Element received is: A0
Element received is: A1
Element received is: A2
Element received is: A3
Element received is: A4 
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us