This method adds the specified element at tail into the deque, to add an element this method waits (if necessary) until the defined waiting time for getting the space available.
offer(e, timeout, unit) method of BlockingDeque Interface in Java.
In this section we will discuss how can offer(e, timeout, unit) method be implemented in BlockingDeque interface in java.
Syntax
boolean offer(E e, long timeout, TimeUnit unit)
This method adds the specified element at tail into the deque, to add an element this method waits (if necessary) until the defined waiting time for getting the space available. This method returns 'true' if a defined element is added successfully or, 'false' if the defined waiting time lapses before space is available. This method is equivalent to offerLast().
Parameter description
e : It takes an element what do you want to insert at last position into deque.
timeout : It is the waiting time that how long to wait before giving up, in units of unit.
unit : It is the unit of time which determines how to interpret the timeout parameter. Written as 'TimeUnit.Seconds' (or, microsecond, milliseconds, nanosecond, etc).
Example of offer(e, timeout, unit) method
In this example we will show you how does offer(e, timeout, unit) method work in BlockingDeque interface. This example will help you to understand how you can insert the specified element with declared waiting time at the last position into the deque.
Example :
package devmanuals.com; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; class OfferTimeUnit implements Runnable { BlockingDeque<Integer> bdq; public OfferTimeUnit(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.offer(i); System.out.println(bdq); System.out.println("Size of deque = "+bdq.size()); try { Thread.sleep(1000); bol = bdq.offer(5,2,TimeUnit.SECONDS); System.out.println("The element is added into the deque : "); Thread.sleep(1000); System.out.println(bol); Thread.sleep(1000); System.out.println("Deque after adding element : "+bdq); System.out.println("Size of deque after adding element = "+bdq.size()); } catch (InterruptedException e) { e.printStackTrace(); } } } public class BdqOfferTimeUnit { public static void main(String[] args) { BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>(); Runnable a = new OfferTimeUnit(bdq); new Thread(a).start(); } }
Output :
Elements of deque are : [0, 1, 2, 3, 4] Size of deque = 5 The element is added into the deque : true Deque after adding element : [0, 1, 2, 3, 4, 5] Size of deque after adding element = 6 |
[ 0 ] Comments