Skip to content

Instantly share code, notes, and snippets.

@benjic
Created June 24, 2015 02:39
Show Gist options
  • Save benjic/2c5b28dbe7bba7838143 to your computer and use it in GitHub Desktop.
Save benjic/2c5b28dbe7bba7838143 to your computer and use it in GitHub Desktop.
A hookey process queue with max wait time and retry.
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ThreadQueue {
public static final int SECONDS = 1000;
private Queue<Runnable> mProcessQueue;
/*
* A private internal class to mock processes. On construction they generate a
* random time amount to sleep for. Upon early termination they whine about their
* time need.
*/
private class PretendProcess implements Runnable {
public static final int MIN_PROCESS_SLEEP_TIME=2;
public static final int MAX_PROCESS_SLEEP_TIME=12;
private int mProcessWaitTime;
private int mProcessID;
/*
* Creates a new mock process with a given identifier
*/
public PretendProcess(int id) {
mProcessID = id;
mProcessWaitTime = new Random().nextInt(MAX_PROCESS_SLEEP_TIME) + MIN_PROCESS_SLEEP_TIME;
}
@Override
public void run() {
try {
// The thread blocks for the required time interval and prints on success
Thread.sleep(mProcessWaitTime * SECONDS );
System.out.println("Process " + mProcessID + " finished successfully in " + mProcessWaitTime + " seconds.");
} catch (InterruptedException e) {
// If the thread is interrupted it complains
System.out.println("Process " + mProcessID + " requried " + mProcessWaitTime + " seconds but was terminated early");
}
}
}
public ThreadQueue(int numberOfProcesses) throws InterruptedException {
// Create a new Queue using a LinkedList
mProcessQueue = new ConcurrentLinkedQueue<Runnable>();
int processWaitTime = 4;
// Populate the queue
for(int i = 1; i <= numberOfProcesses; i++) {
mProcessQueue.add(new PretendProcess(i));
}
// Consume the queue
for (Runnable r : mProcessQueue) {
// Create thread and begin
Thread t = new Thread(r);
t.start();
// Block calling thread and wait for thread to finish
t.join(processWaitTime * SECONDS);
if (t.isAlive()) {
// If the thread has not finished by the end of the join we
// interrupt the thread, add the runnable to the end of the queue
// and back off the max wait time by a linear amount. This allows
// the program to retry processes that took too long.
t.interrupt();
mProcessQueue.add(r);
processWaitTime++;
}
}
}
public static void main(String[] args) throws InterruptedException {
// Create a ThreadQueue with 10 Processes
ThreadQueue tq = new ThreadQueue(10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment