DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

๐Ÿง  Mastering Data Structures in Java โ€” Part 5: Queue

๐Ÿ” What Is a Queue?

A Queue is a First-In, First-Out (FIFO) data structure.
That means the first element added is the first one removed โ€” just like waiting in line at a coffee shop โ˜•.

Think of it as a pipeline:

  • Enqueue โ†’ add to the end
  • Dequeue โ†’ remove from the front

In Java, the Queue is part of the java.util package and is represented by the Queue interface.


โš™๏ธ Basic Example

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<String> orders = new LinkedList<>();

        orders.add("Order #1");
        orders.add("Order #2");
        orders.add("Order #3");

        System.out.println("Orders: " + orders); // [Order #1, Order #2, Order #3]

        System.out.println("Serving: " + orders.poll()); // removes Order #1
        System.out.println("Next in line: " + orders.peek()); // Order #2
    }
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿงฉ Methods:

add(e) โ†’ Add element to queue

poll() โ†’ Remove and return front element (returns null if empty)

peek() โ†’ View front element (without removing)

remove() โ†’ Remove front element (throws exception if empty)


โš™๏ธ Queue Implementations in Java

Java offers several ways to implement a Queue โ€” each with different use cases:

Class Type Description
LinkedList Non-blocking Basic FIFO queue
PriorityQueue Non-blocking Orders elements by priority
ArrayDeque Non-blocking Double-ended queue (Deque)
ConcurrentLinkedQueue Thread-safe Non-blocking queue for concurrency
BlockingQueue Thread-safe Used in producer-consumer patterns

โš™๏ธ Example: PriorityQueue

import java.util.PriorityQueue;

public class PriorityExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        pq.add(30);
        pq.add(10);
        pq.add(20);

        while (!pq.isEmpty()) {
            System.out.println(pq.poll());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

โœ… Output:

10
20
30
Enter fullscreen mode Exit fullscreen mode

Elements are automatically ordered โ€” smallest comes first!


๐Ÿ” Real-World Use Cases of Queues

Queues are everywhere โ€” in both system-level and application-level designs:

๐Ÿ–ฅ 1. Task Scheduling

OS schedulers and thread pools use queues to manage jobs in order.

๐Ÿ“ฌ 2. Messaging Systems

Message brokers (like Kafka, RabbitMQ, or ActiveMQ) rely on queues to store and process messages sequentially.

๐ŸŒ 3. Web Servers

Web servers manage client requests using queues to handle high traffic efficiently.

๐ŸŽฎ 4. Gaming

Queues manage player actions, events, and network messages to ensure order.

๐Ÿงฎ 5. Producerโ€“Consumer Pattern

A background thread produces data, another consumes it โ€” synchronized via a queue.


โš™๏ธ Example: Producerโ€“Consumer with Queue

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();

        // Producer
        for (int i = 1; i <= 5; i++) {
            queue.add(i);
            System.out.println("Produced: " + i);
        }

        // Consumer
        while (!queue.isEmpty()) {
            System.out.println("Consumed: " + queue.poll());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฎ Time Complexity

Operation Time Complexity
Enqueue O(1)
Dequeue O(1)
Peek O(1)
Search O(n)

โš ๏ธ Common Mistakes

โŒ Using add() and not handling exceptions when queue is full.

โŒ Confusing poll() and remove() โ€” poll() is safer.

โŒ Using wrong queue type for concurrency.

โŒ Expecting random access (queues donโ€™t support indexes).


โš–๏ธ Stack vs Queue

Feature Stack Queue
Principle LIFO FIFO
Example Browser Back Button Task Scheduling
Key Methods push(), pop(), peek() add(), poll(), peek()

๐Ÿ’ก Final Thought

The Queue is the backbone of many real-world systems โ€” from task schedulers to message queues.
It models the flow of data, requests, and actions in a natural and organized way.

Mastering Queues helps you think like a system designer โ€” not just a programmer. ๐Ÿง ๐Ÿ’ช

Top comments (0)