Java: Implement own message queue (threadsafe)
Posted
by
derMax
on Stack Overflow
See other posts from Stack Overflow
or by derMax
Published on 2012-12-02T16:59:22Z
Indexed on
2012/12/02
17:04 UTC
Read the original article
Hit count: 319
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?
© Stack Overflow or respective owner