Skip to content
Create a gist now

Instantly share code, notes, and snippets.

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));
private Thread senderThread;
private void startSenderThread(){
if(senderThread == null || !senderThread.isAlive()){
senderThread = new Thread(){
public void run() {
private void loopSendMessage(){
Message queuedMessage;
try {
queuedMessage = messageQueue.poll(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
EasyLog.e(SMSSenderDaemon.this, "SenderThread interrupted while polling.", e);
if(queuedMessage != null)
// 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
Something went wrong with that request. Please try again.