Skip to content

Instantly share code, notes, and snippets.

@abonander
Last active December 21, 2015 13:18
Show Gist options
  • Save abonander/6311492 to your computer and use it in GitHub Desktop.
Save abonander/6311492 to your computer and use it in GitHub Desktop.
The part of my code that deals with threading. The sendMessage() method can be called from any thread and at any time. It posts a new message to send to the message queue and starts the sender thread if it isn't running. The sender thread polls the queue with a timeout, and processes the messages. If there are no more messages in the queue, the …
private final LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();
// The sender argument is an enum describing who sent the message: the user, the app, or the person on the other end.
public void sendMessage(String address, String message, Sender sender) {
messageQueue.offer(Message.create(address, message, sender));
startSenderThread();
}
private Thread senderThread;
private void startSenderThread(){
if(senderThread == null || !senderThread.isAlive()){
senderThread = new Thread(){
@Override
public void run() {
loopSendMessage();
}
};
senderThread.start();
}
}
private void loopSendMessage(){
Message queuedMessage;
while(!Thread.interrupted()){
try {
queuedMessage = messageQueue.poll(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
EasyLog.e(SMSSenderDaemon.this, "SenderThread interrupted while polling.", e);
continue;
}
if(queuedMessage != null)
sendOrQueueMessage(queuedMessage);
else
break;
}
}
// Queue in this context means storing the message in the database
// so it can be sent later.
private void sendOrQueueMessage(Message message){
//Irrelevant code omitted.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment