Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Implement own message queue (threadsafe)

The task is to implement my own messagequeue that is thread safe.

My approach:

public class MessageQueue {
    /**
     * Number of strings (messages) that can be stored in the queue.
     */
    private int capacity;

    /**
     * The queue itself, all incoming messages are stored in here.
     */
    private Vector<String> queue = new Vector<String>(capacity);

    /**
     * Constructor, initializes the queue.
     * 
     * @param capacity The number of messages allowed in the queue.
     */
    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    /**
     * Adds a new message to the queue. If the queue is full,
     * it waits until a message is released. 
     *
     * @param message
     */
    public synchronized void send(String message) {
        //TODO check
    }

    /**
     * Receives a new message and removes it from the queue. 
     *
     * @return
     */
    public synchronized String receive() {
        //TODO check
        return "0";
    }
}

If the queue is empty and I call remove(), I want to call wait() so that another thread can use the send() method. Respectively, I have to call notifyAll() after every iteration.

Question: Is that possible? I mean does it work that when I say wait() in one method of an object, that I can then execute another method of the same object?

And another question: Does that seem to be clever?

like image 372
derMax Avatar asked Nov 29 '25 22:11

derMax


1 Answers

Question: Is that possible? I mean does it work that when I say wait() in one method of an object, that I can then execute another method of the same object?

Yes! That is exactly how wait and notify/notifyAll are designed. If you call wait() on an object then that thread blocks until another thread calls notify/notifyAll on the same object.

And another question: Does that seem to be clever?

Yes! This is precisely how I would (and have) implemented a message queue using low-level Java operations.


If you're interested, there's a BlockingQueue class in the standard library that does exactly this. If you just want to use such a class, use BlockingQueue. If your goal is to learn how to implement a message queue, though, continue with your approach, which is exactly right.

public interface BlockingQueue<E>
extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

like image 54
John Kugelman Avatar answered Dec 01 '25 11:12

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!