add(e) method of BlockingDeque Interface in Java.

add(e) method of BlockingDeque Interface in Java.


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

An element is to be inserted into the underlying deque without breaking the capacity limitation of deque. In such case if there is currently no space available in

add(e) method of BlockingDeque Interface in Java.

In this section we will discuss how can add(e) method be implemented in BlockingDeque interface in java.

Syntax

boolean add(E e) 

This method adds a specific element at the tail into the deque if currently space is available.

An element is to be inserted into the underlying deque without breaking the capacity limitation of deque. In such case if there is currently no space available in deque, this method does not adds the element and displays an 'IllegalStateException' exception otherwise, returns 'true' upon successful addition of element into deque.

Parameter description

e : It takes an element what do you want to insert into deque.

Example of add(E e) method

In this example we will show you how does add(e) method work in BlockingDeque interface. This example will help you to understand how a specified element can be added at tail into the deque. Through this example we will also show you what does it return when a specified element is added successfully.

Example :

package devmanuals.com;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
class Add implements Runnable 
{
  BlockingDeque<Integer> bdq;
  public Add(BlockingDeque<Integer> bdq
  {
    this.bdq = bdq;
  }
  public void run() 
  {
    System.out.println("Elements of deque are : ");
    int i;
    boolean bol=false;
    for(i=0; i<5;i++)
     bdq.add(i);
      System.out.println(bdq);
      System.out.println("Size of deque = "+bdq.size());
    try {
       Thread.sleep(500);
        bol = bdq.add(5);
      }
      catch (InterruptedException e
      {
        e.printStackTrace();
      }
      System.out.println("Deque after adding element : "+bdq);
      System.out.println("Size of deque after adding element = "+bdq.size());
      System.out.println("The element is added into the deque : "+bol);
  }
}
public class BdqAdd {
  public static void main(String[] args) {
    BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>();
    Runnable a = new Add(bdq);
    new Thread(a).start();
    try {
      Thread.sleep(300);
      
    catch (InterruptedException e
    {
      e.printStackTrace();
    }
  }
}

Output :

Elements of deque are :

[0, 1, 2, 3, 4]

Size of deque = 5

Deque after adding element : [0, 1, 2, 3, 4, 5]

Size of deque after adding element = 6

The element is added into the deque : true 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics