This method adds a specific element at head into the deque, to add an element this method waits (if necessary) until the defined waiting time for becoming the space available.
offerFirst(e, timeout, unit) method of BlockingDeque Interface in Java.
In this section we will discuss how can offerFirst(e, timeout, unit) method be implemented in BlockingDeque interface in java.
Syntax
boolean offerFirst(E e, long timeout, TimeUnit unit)
This method adds a specific element at head into the deque, to add an element this method waits (if necessary) until the defined waiting time for becoming the space available. This method returns 'true' if an element is added successfully or, 'false' if the specified waiting time lapses before space is available.
Parameter description
e : It takes an element what do you want to insert at first 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 offerFirst(e, timeout, unit) method
In this example we will show you how does offerFirst(e, timeout, unit) method work in BlockingDeque interface. This example will help you to understand how can you insert the specified element with declared waiting time at first position into the deque.
Example :
package devmanuals.com; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; class OfferFirstTimeUnit implements Runnable { BlockingDeque<Integer> bdq; public OfferFirstTimeUnit(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.offerFirst(5,1,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 BdqOfferFirstTimeUnit { public static void main(String[] args) { BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>(); Runnable a = new OfferFirstTimeUnit(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 : [5, 0, 1, 2, 3, 4] Size of deque after adding element = 6 |
[ 0 ] Comments