I'm making a simple server-client application. I'm handling the message queue this way (class MessageQueue
):
private Vector<String> messages;
//Runs from any thread
public void add(String message) {
synchronized(messages) {
messages.add(message);
//This is only way to unstuck messages.wait()
messages.notifyAll();
}
}
//Runs from special thread
private void readQueue() {
Log.debug("Waiting for messages to send.");
while(run) {
synchronized(messages) {
//STUCK HERE!
try {messages.wait();}catch(InterruptedException e) {}
//send messages
...
}
}
}
I designed the code using this answer, but it's wrong or I haven't interpreted it correctly. Here's what happens:
- Thread
readQueue
starts. - Thread
readQueue
blocksmessages
bysynchronized
block. - Thread
readQueue
blocks itself onmessages.wait()
. - Another thread calls
add("...")
method. - Another thread gets stuck on
synchronized
block.
The messages.notifyAll()
can never be called. Of course, originally, before searching, I was trying to do this:
//Runs from special thread
private void readQueue() {
Log.debug("Waiting for messages to send.");
while(run) {
//Wait before getting noticed of new message
try {messages.wait();}catch(InterruptedException e) {}
//Block messages, read them, clear them
synchronized(messages) {
//send messages
...
}
}
}
This throws illegal monitor exception, which forces me to put wait
into synchronized
- and we're just where we begun - stuck.