// Implemented as a solution to the question in: http://stackoverflow.com/questions/13005964/thread-pool-where-workers-are-both-producers-and-consumers import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Test { public void startTest(long maxComputationTimeMS, long maxJobTimeMS, int maxBranchingFactor, int numOfThreads) { // print the session details System.out.println("Starting a new session where:"); System.out.println("\tMaximum computation time is: " + maxComputationTimeMS + "ms."); System.out.println("\tJobs will take N milliseconds to complete, where [0 <= N < " + maxJobTimeMS + "]."); System.out.println("\tJobs may spawn N new jobs, where [0 <= N < " + maxBranchingFactor +"]."); System.out.println("\tThe executor will use a pool of " + numOfThreads + " threads."); // a new work queue which orders tasks based on compareTo() PriorityBlockingQueue queue = new PriorityBlockingQueue(); // a new thread pool executor using the above queue with a custom handler TestExecutor executor = new TestExecutor(numOfThreads, numOfThreads, 1000, TimeUnit.MILLISECONDS, queue, new CancelledJobHandler()); // schedule a new comparable work unit for execution executor.executeJob(new WorkUnit(maxJobTimeMS, maxBranchingFactor, executor)); // print out a start of work message System.out.println("Work started..."); // wait for the work to complete then print the completion status if(executor.awaitCompletion(maxComputationTimeMS, TimeUnit.MILLISECONDS)) { System.out.println("Timeout encountered, main thread exiting..."); } else { System.out.println("No more jobs queued, main thread exiting..."); } // shut the executor down executor.shutdownNow(); // await at most one second for the termination of the executor try { executor.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } // print whether or not the executor terminated in time if(executor.isShutdown()) { System.out.println("Executor shut down in a timely manner."); } else { System.err.println("Executor failed to shut down in a timely manner."); } } // start the test with a maximum computation time of 10 seconds public static void main(String argv[]) throws InterruptedException { Test t = new Test(); t.startTest(5000, 1000, 4, 3); } // a custom exception handler to be used if the executor is terminated prematurely public class CancelledJobHandler implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.err.println("Job cancelled: " + r); } } }