Home  >  Core Java

Example of LinkedBlockingDeque in Java

By Arvind Rai, December 17, 2012
On this page we will provide example of LinkedBlockingDeque in java. LinkedBlockingDeque has been introduced in JDK 1.6. It belongs to java.util.concurrent package. LinkedBlockingDeque is a BlockingDeque which works with linked nodes. Here we will provide complete example of LinkedBlockingDeque.

BlockingDeque

BlockingDeque is a Deque which supports blocking operation. Deque is a queue that supports insertion and deletion at both sides. BlockingDeque means 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. LinkedBlockingDeque can instantiated as unbounded as well as bounded by passing the capacity.

add(E e): Inserts the given element at the 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 of LinkedBlockingDeque

Find the example of LinkedBlockingDeque.
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
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us