Skip to content

Instantly share code, notes, and snippets.

@john77eipe
Created September 25, 2016 19:23
Show Gist options
  • Save john77eipe/8ee30b6e14e72dce9a4b966cea4a06f4 to your computer and use it in GitHub Desktop.
Save john77eipe/8ee30b6e14e72dce9a4b966cea4a06f4 to your computer and use it in GitHub Desktop.
Threading fun!!!
package testex;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestingExecutorService {
// making this object as static as you don't want multiple services created
// for each request
static ExecutorService executor = new ThreadPoolExecutor(1, 1,
1, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(100),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {
System.out.println("Execution rejected");
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while submitting task", e);
}
}
});
public static void main(String[] args) throws InterruptedException {
new TestingExecutorService().doTask();
new TestingExecutorService().doTask();
Thread.sleep(5000);
new TestingExecutorService().doTask();
}
public void doTask() {
System.out.println("doTask()");
System.out.println("Completed tasks "
+ ((ThreadPoolExecutor) executor).getCompletedTaskCount());
System.out.println("Total threads in execution"
+ ((ThreadPoolExecutor) executor).getPoolSize());
System.out.println("Scheduled tasks "
+ ((ThreadPoolExecutor) executor).getTaskCount());
// Creating separate Callable thread job wrapping tasks
// job for non-blocking execution
ExecutorJob task = new ExecutorJob();
List<Callable<String>> executorJobs = new ArrayList<Callable<String>>();
executorJobs.add(task);
// submitting jobs to executor for non-blocking execution
for (Callable<String> job : executorJobs) {
executor.submit(job);
}
//executor.shutdown(); //if shutdown gets called - no more tasks are accepted
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
List<Runnable> droppedTasks = executor.shutdownNow();
System.out.println("Shutdown hook called. Dropped tasks: "+droppedTasks.size());
}
});
}
private class ExecutorJob implements Callable<String> {
public String call() throws Exception {
System.out.println("task started");
Thread.sleep(1000);
System.out.println("task finished");
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment