Java Blocking Queues

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

1. Thread safe
2. Allow duplicates
3. Not allowed null values

   

Types

  • ArrayBlockingQueue
  • DelayQueue
  • LinkedBlockingQueue
  • PriorityBlockingQueue
  • SynchronousQueue

Example

package com.vinod.test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BlockingQueueExamples {
   public static void main(String[] args) throws InterruptedException, ExecutionException {
      BlockingQueue<String> bq = new ArrayBlockingQueue<String>(1000);
      ExecutorService exec = Executors.newFixedThreadPool(2);
      exec.submit(new ConsumerThread(bq));
      exec.submit(new ProducerThread(bq));

   }

}

class ProducerThread implements Callable<Object> {
   private BlockingQueue<String> blockingQueue;

   public ProducerThread(BlockingQueue<String> blockingQueue) {
      this.blockingQueue = blockingQueue;
   }

   public Object call() throws Exception {
      System.out.println("Producer Started:");
      Thread.sleep(1000);
      blockingQueue.put("vinod");
      Thread.sleep(1000);
      blockingQueue.put("vinod1");
      Thread.sleep(1000);
      blockingQueue.put("vinod2");
      return null;
   }

}

class ConsumerThread implements Callable<Object> {
   private BlockingQueue<String> blockingQueue;

   public ConsumerThread(BlockingQueue<String> blockingQueue) {
      this.blockingQueue = blockingQueue;
   }

   public Object call() throws Exception {
      System.out.println("Consumer Started:");
      System.out.println(blockingQueue.take());
      System.out.println(blockingQueue.take());
      System.out.println(blockingQueue.take());

      return null;
   }

}

Output

Consumer Started:
Producer Started:
vinod
vinod1
vinod2

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts