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.
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 theput()
method ofBlockingQueue
. If the queue is full, the calling producer thread will block (wait) until space becomes available.consume()
: Uses thetake()
method ofBlockingQueue
. 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.
- 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.
- Compile: Compile the Java files using a Java Development Kit (JDK):
javac src/main/java/com/gireesh/queue/*.java
- Run the Demo: Execute the
MessageQueueDemo
class to see multiple producers and consumers interacting with the queue: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.java -cp src/main/java com.gireesh.queue.MessageQueueDemo
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 usingLinkedBlockingQueue
.src/main/java/com/gireesh/queue/MessageQueueDemo.java
: A demonstration class showing concurrent producers and consumers.