June 28, 2022

LinkedTransferQueue in Java With Examples

LinkedTransferQueue in Java is an implementation of the TransferQueue interface and is part of java.util.concurrent package. It was added in Java 7.

TransferQueue interface in Java

TransferQueue interface which extends BlockingQueue interface adds the capability where producers may wait for consumers to receive elements.

In BlockingQueue implementations like ArrayBlockingQueue, PriorityBlockingQueue there are operations that wait if the queue is empty when retrieving an element, and wait for space to become available in the queue when storing an element. In the TransferQueue there are operations that block at the element level too.

Java TransferQueue Methods

Apart from the methods inherited from the BlockingQueue, TransferQueue adds the following methods to add the capability where the thread waits until the element is consumed by another thread.

  • transfer(E e)- Transfers the element to a consumer, waiting if necessary to do so.
  • tryTransfer(E e)- Transfers the specified element immediately if there exists a consumer already waiting to receive it otherwise returns false
  • tryTransfer(E e, long timeout, TimeUnit unit)- Transfers the specified element immediately if there exists a consumer already waiting to receive it. Waits until the element is received by a consumer, returning false if the specified wait time elapses before the element can be transferred.

TransferQueue also has the following querying methods-

  • hasWaitingConsumer()- Returns true if there is at least one consumer waiting to receive an element.
  • getWaitingConsumerCount()- Returns an estimate of the number of consumers waiting to receive elements.

LinkedTransferQueue in Java

LinkedTransferQueue is an unbounded TransferQueue which stores its elements as linked nodes where each node stores a reference to the next node. Elements in this queue are ordered in FIFO (first-in-first-out) manner. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.

Java LinkedTransferQueue constructors

  • LinkedTransferQueue()- Creates an initially empty LinkedTransferQueue.
  • LinkedTransferQueue(Collection<? extends E> c)- Creates a LinkedTransferQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.

LinkedTransferQueue Java example

Here is an example of producer-consumer in Java using LinkedTransferQueue. In the consumer thread there is a sleep method with time passed as 2 seconds to make the consumer thread pause for 2 seconds even then the producer thread waits for the element to be retrieved by the consumer.

public class LinkedTQ {
  public static void main(String[] args) {
    TransferQueue<Integer> tQueue = new LinkedTransferQueue<>();
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new LinkedProducer(tQueue));
    executor.execute(new LinkedConsumer(tQueue));
    executor.shutdown();
  }
}

//Producer
class LinkedProducer implements Runnable{
  TransferQueue<Integer> tQueue;
  LinkedProducer(TransferQueue<Integer> tQueue){
    this.tQueue = tQueue;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      try {
        System.out.println("Adding to queue-" + i);
        tQueue.transfer(i);    
        TimeUnit.MILLISECONDS.sleep(500);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
//Consumer
class LinkedConsumer implements Runnable{
  TransferQueue<Integer> tQueue;
  LinkedConsumer(TransferQueue<Integer> tQueue){
    this.tQueue = tQueue;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      try {
        // Delay of 2 seconds
        TimeUnit.SECONDS.sleep(2);
        System.out.println("Consumer retrieved- " + tQueue.take());				
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
     }
  }
}
Output
Adding to queue-0
Consumer retrieved- 0
Adding to queue-1
Consumer retrieved- 1
Adding to queue-2
Consumer retrieved- 2
Adding to queue-3
Consumer retrieved- 3
Adding to queue-4
Consumer retrieved- 4

That's all for the topic LinkedTransferQueue in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment