Java Collections Framework- BlockingDeque Interface

Java Collections Framework- BlockingDeque Interface


Posted in : Core Java Posted on : February 23, 2011 at 3:29 PM Comments : [ 0 ]

A BlockingDeque is represented by the java.util.concurrent.BlockingDeque interface. This interface is thread-safe and does not permit null elements.

Java Collections Framework- BlockingDeque Interface

In java, BlockingDeque interface is similar to the Deque interface but, this interface has added some additional functions. When we are trying to insert an element into the BlockingDeque, the elements may have to wait until the space becomes available to insert an element due to if the BlockingDeque is already full. There are four forms of BlockingDeque methods in which they may comes :

  • Methods throws an exception
  • Methods returns a special value (null/false depends upon operations).
  • Methods that blocks the current thread (Waits indefinitely for space to available).
  • Methods that times out (Waits for a given time for space to available).

In java, java.util.concurrent.BlockingDeque represents the thread-safe BlockingDeque interface and it does not also permit null elements 

This interface provides some methods which are as follows :

Here is the simple example of BlockingDeque interface :-

Example :

package devmanuals.com;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
class implements Runnable
   {
  String name;
  BlockingDeque<Integer> dq;
public A(String name, BlockingDeque<Integer> dq){
    this.name = name;
    this.dq = dq;
  }
  public void run(){
    for (int i = 0; i < 5; i++){
      try {
        dq.putFirst(i);
        System.out.println(name + " puts " + i);
        Thread.sleep(500);
        
      catch (InterruptedException e){
        e.printStackTrace();
      }
    }
  }
}
class implements Runnable {
  String name;
  BlockingDeque<Integer> dq;
public B(String name, BlockingDeque<Integer> dq){
    this.name = name;
    this.dq = dq;
  }
  public void run() {
    for (int i = 0; i < 5; i++){
      try {
        int j = dq.takeLast();
        System.out.println(name + " takes " + j);
        Thread.sleep(1000);
        }
      catch (InterruptedException e){
        e.printStackTrace();
      }
    }
  }
}
public class BlockingDequeDemo {
  public static void main(String[] args) {
    BlockingDeque<Integer> dq = new LinkedBlockingDeque<Integer>(5);
    Runnable a = new A("A", dq);
    Runnable b = new B("B", dq);
    new Thread(a).start();
    try {
      Thread.sleep(300);
      
    catch (InterruptedException e){
      e.printStackTrace();
    }
    new Thread(b).start();
  }
}

Output :

A puts 0

B takes 0

A puts 1

A puts 2

B takes 1

A puts 3

A puts 4

B takes 2

B takes 3

B takes 4 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics