Hackforge Academy

Category: java

Understanding Producer-Consumer

Published on 27 Oct 2026

Explanation

The producer-consumer pattern separates creating data from processing it. Producers place items in a shared buffer, and consumers remove them. A bounded buffer prevents producers from overwhelming consumers.

Code:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(5);
        new Thread(() -> { try { queue.put("Job-1"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start();
        new Thread(() -> { try { System.out.println(queue.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start();
    }
}

Explanation

BlockingQueue provides thread-safe put() and take() operations. put() waits when a bounded queue is full, so a producer naturally slows down when consumers cannot keep up.

Code:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
        queue.put(100);
        queue.put(200);
        System.out.println("Queued items: " + queue.size());
    }
}

Explanation

take() waits while the queue is empty and returns the next available item. This avoids manual wait/notify coordination for many standard producer-consumer use cases.

Code:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ConsumerDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
        queue.put("Order-101");
        String order = queue.take();
        System.out.println("Processing " + order);
    }
}

Explanation

A bounded queue limits how much work can accumulate in memory. When the queue is full, producers block or use timed offer() calls, providing a form of backpressure that helps protect downstream consumers.

Code:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class BackpressureDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);
        queue.put(1);
        boolean accepted = queue.offer(2, 100, TimeUnit.MILLISECONDS);
        System.out.println("Second item accepted: " + accepted);
    }
}

Explanation

ExecutorService can run producer and consumer tasks while a BlockingQueue safely transfers work between them. In a real service, define a shutdown strategy so consumers can finish or stop cleanly.

Code:

import java.util.concurrent.*;

public class ProducerConsumerPoolDemo {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.submit(() -> { try { queue.put(7); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
        pool.submit(() -> { try { System.out.println("Consumed " + queue.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
        pool.shutdown();
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community