/java-message-queue

A simple, thread-safe, in-memory blocking message queue in Java.

Primary LanguageJava

Java In-Memory Blocking Message Queue

Project Overview

This project provides a simple, thread-safe, in-memory message queue implementation in Java. It demonstrates the producer-consumer pattern using a fixed-size buffer (the queue) and blocking operations.

How it Works

This implementation leverages Java's built-in java.util.concurrent.BlockingQueue interface, specifically using LinkedBlockingQueue.

  • Bounded Capacity: The queue is initialized with a fixed maximum capacity.
  • Blocking Operations:
    • produce(message): Uses the put() method of BlockingQueue. If the queue is full, the calling producer thread will block (wait) until space becomes available.
    • consume(): Uses the take() method of BlockingQueue. If the queue is empty, the calling consumer thread will block (wait) until a message is available.
  • Thread Safety: LinkedBlockingQueue is inherently thread-safe, handling all the necessary synchronization internally.
  • FIFO: Messages are consumed in the First-In, First-Out order they were produced.

Benefits & Relevance

  • Producer-Consumer Pattern: Demonstrates a fundamental concurrency pattern used in many distributed systems and applications.
  • Concurrency Practice: Provides practical application of Java's concurrent collections (BlockingQueue) and thread management (ExecutorService).
  • System Design Insight: Helps understand the basics of message queuing systems, which are crucial components in decoupling services and managing asynchronous communication.
  • Interview Relevance: Concepts like blocking queues, thread safety, and producer-consumer are common topics in software engineering interviews, particularly for backend and systems roles.

How to Use/Run

  1. Compile: Compile the Java files using a Java Development Kit (JDK):
    javac src/main/java/com/gireesh/queue/*.java
  2. Run the Demo: Execute the MessageQueueDemo class to see multiple producers and consumers interacting with the queue:
    java -cp src/main/java com.gireesh.queue.MessageQueueDemo
    The demo simulates producers adding messages and consumers removing them concurrently, showing how the queue size changes and how threads block when the queue is full or empty.

Files

  • src/main/java/com/gireesh/queue/MessageQueue.java: The interface defining the basic queue operations.
  • src/main/java/com/gireesh/queue/InMemoryBlockingMessageQueue.java: The concrete implementation using LinkedBlockingQueue.
  • src/main/java/com/gireesh/queue/MessageQueueDemo.java: A demonstration class showing concurrent producers and consumers.