Home  >  Java 7

ConcurrentLinkedDeque Java Example

By Arvind Rai, January 08, 2014
java.util.concurrent.ConcurrentLinkedDeque has been introduced in JDK 7 and is the part of java collection framework. ConcurrentLinkedDeque is an unbounded concurrent deque. ConcurrentLinkedDeque works on the basis of linked nodes. As ConcurrentLinkedDeque is thread safe so removal, insertion and other operation can be performed concurrently. Null values or not permitted in this collection. Iterating values from this collection will not return correct values if at the same time there is adding or removal going on. However ConcurrentLinkedDeque is good choice when we are looking for adding and deleting in concurrent environment. Find some method description.

add() and offer() in ConcurrentLinkedDeque

As ConcurrentLinkedDeque is unbounded, so there is no difference in add and offer in this context. add() will not throw exception because there is always space to add element and offer() will always be successful to add element.

poll() in ConcurrentLinkedDeque

poll() retrieves and removes the head of ConcurrentLinkedDeque i.e first element . It returns null if there is no element.

peek () in ConcurrentLinkedDeque

peek() method will return the first element of ConcurrentLinkedDeque but does not remove it. It will return null if there is no element.

Element() in ConcurrentLinkedDeque

element() method throws exception when there is no element in ConcurrentLinkedDeque otherwise it is same as peek() method.
ConcurrentLinkedDequeDemo.java
package com.concretepage.util.concurrent;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentLinkedDequeDemo {
	static ConcurrentLinkedDeque<String> cld=new ConcurrentLinkedDeque<String>();
	public static void main(String[] args) {
		ExecutorService exService = Executors.newFixedThreadPool(2);
		ThreadOne elementAdd = new ConcurrentLinkedDequeDemo().new ThreadOne();
		ThreadTwo elementGet = new ConcurrentLinkedDequeDemo().new ThreadTwo();
		exService.execute(elementAdd);
		exService.execute(elementGet);
		exService.shutdown();
	}
	class ThreadOne implements Runnable{
		@Override
		public void run() {
			for(int i=0;i<5;i++){
					cld.add("A"+i);
			}
		}
	}
	class ThreadTwo implements Runnable{
		@Override
		public void run() {
			for(int i=0;i<5;i++){
					String s= cld.poll();
					System.out.println("Element received is: "+s);
			}
		}
	}
}
 
I have two threads, one is adding the element and other is retrieving and removing the element. All these are happening concurrently. Find the output.
Element received is: null
Element received is: A0
Element received is: A1
Element received is: A2
Element received is: A3
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us