I would rethink your solution, using ScheduledExecutorService for executing a Runnable in background. This class also allows executing periodic actions at a fixed rate:
Your Runnable class:
public void run() {
for (Object message: messages) {
try {
if (message instanceof Byte)
out.writeByte((Byte)message);
else if (message instanceof Boolean)
out.writeBoolean((Boolean)message);
else if (message instanceof String)
out.writeUTF((String)message);
else if (message instanceof Integer)
out.writeInt((Integer)message);
else if (message instanceof Long)
out.writeLong((Long)message);
} catch (IOException e) {}
}
synchronized (newMessages) {
messages.clear();
messages.addAll(newMessages);
newMessages.clear();
}
}
public void write(Object message) {
synchronized (newMessages) {
newMessages.add(message);
}
}
Then, for invoking the Runnable:
Runnable sender=new MyMessageSender(); //or whatever your class is called
int threadPoolSize=1; //number of Threads you want to launch
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(threadPoolSize);
final ScheduledFuture<?> senderHandle =
scheduler.scheduleAtFixedRate(sender, 10, 10, SECONDS); //from now in 10 senconds, execute sender every 10 seconds