Home > Java > javaTutorial > How Can Java\'s `wait()` and `notify()` Methods Be Used to Implement a Blocking Queue?

How Can Java\'s `wait()` and `notify()` Methods Be Used to Implement a Blocking Queue?

Barbara Streisand
Release: 2024-11-23 09:42:31
Original
723 people have browsed it

How Can Java's `wait()` and `notify()` Methods Be Used to Implement a Blocking Queue?

Using Wait() and Notify() in Java: A Scenario with Queues

Question:

Can you provide a comprehensive walkthrough of how to implement the wait() and notify() methods with a Queue?

Answer:

Principle of Wait() and Notify()

Wait() and notify() enable thread coordination by having threads wait for specific conditions to be met before proceeding. In this case, we're interested in creating a blocking queue that enforces capacity limitations.

Implementation

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<>();
    private int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public synchronized void put(T element) throws InterruptedException {
        while (queue.size() == capacity) {
            wait();
        }

        queue.add(element);
        notify(); // Notify waiting threads
    }

    public synchronized T take() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }

        T item = queue.remove();
        notify(); // Notify waiting threads
        return item;
    }
}
Copy after login

How It Works

  • Put() Method: If the queue is full, the current thread waits until it receives a notification that space is available.
  • Take() Method: If the queue is empty, the current thread waits until it receives a notification that an element is available.

Note: Ensure that the wait() and notify() calls are synchronized on the same object and placed within a while loop to handle spurious wake-ups.

Java 1.5 Concurrent Features

Java 1.5 introduced the java.util.concurrent package, providing higher-level abstractions for thread coordination. Here's an updated version of the example:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<>();
    private int capacity;
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public void put(T element) throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() == capacity) {
                notFull.await();
            }

            queue.add(element);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                notEmpty.await();
            }

            T item = queue.remove();
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
}
Copy after login

This approach uses locks and conditions for improved thread coordination.

Consider the BlockingQueue Interface

If you require a blocking queue, consider using an implementation of the Java BlockingQueue interface, which provides a standard implementation with thread-safe and capacity-controlled operations.

The above is the detailed content of How Can Java's `wait()` and `notify()` Methods Be Used to Implement a Blocking Queue?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template