package chat;
import java.util.LinkedList;
import common.util.Event;
/*
* it is necessary that chat messages are buffered before sending them because the
* ControlledOutputStream could be blocking, but the GUI must continue to work.
*/
public class MessageBufferThread extends Thread
{
private LinkedList<String> messageBuffer;
private Event event;
private volatile boolean terminating;
private MessageSenderInterface sender;
public MessageBufferThread(MessageSenderInterface sender)
{
super("Message Buffer");
messageBuffer = new LinkedList<String>();
event = new Event();
this.sender = sender;
start();
}
public void run()
{
terminating = false;
while (!terminating)
{
emptyBuffer();
event.waitCondition();
}
}
private void emptyBuffer()
{
while (extractMessage())
{
}
}
private boolean extractMessage()
{
String message;
synchronized (messageBuffer)
{
if (messageBuffer.isEmpty())
{
return false;
}
message = messageBuffer.removeLast();
}
sender.sendMessage(message);
return true;
}
public void queueMessage(String message)
{
synchronized (messageBuffer)
{
messageBuffer.addLast(message);
}
event.notifyCondition();
}
public void terminate()
{
terminating = true;
event.notifyCondition();
}
}