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?
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.
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.