Tutorial by Examples

Executors accept a java.lang.Runnable which contains (potentially computationally or otherwise long-running or heavy) code to be run in another Thread. Usage would be: Executor exec = anExecutor; exec.execute(new Runnable() { @Override public void run() { //offloaded work, no need t...
A common Executor used is the ThreadPoolExecutor, which takes care of Thread handling. You can configure the minimal amount of Threads the executor always has to maintain when there's not much to do (it's called core size) and a maximal Thread size to which the Pool can grow, if there is more work t...
If your computation produces some return value which later is required, a simple Runnable task isn't sufficient. For such cases you can use ExecutorService.submit(Callable<T>) which returns a value after execution completes. The Service will return a Future which you can use to retrieve the r...
The ScheduledExecutorService class provides a methods for scheduling single or repeated tasks in a number of ways. The following code sample assume that pool has been declared and initialized as follows: ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); In addition to the nor...
If you try to submit tasks to a shutdown Executor or the queue is saturated (only possible with bounded ones) and maximum number of Threads has been reached, RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) will be called. The default behavior is that you'll get a Rej...
Generally execute() command is used for fire and forget calls (without need of analyzing the result) and submit() command is used for analyzing the result of Future object. We should be aware of key difference of Exception Handling mechanisms between these two commands. Exceptions from submit() ar...
ExecutorService ExecutorService executor = Executors.newFixedThreadPool(50); It is simple and easy to use. It hides low level details of ThreadPoolExecutor. I prefer this one when number of Callable/Runnable tasks are small in number and piling of tasks in unbounded queue does not increase m...
Let's have a look at various options to wait for completion of tasks submitted to Executor ExecutorService invokeAll() Executes the given tasks, returning a list of Futures holding their status and results when everything is completed. Example: import java.util.concurrent.*; import ja...
Executors returns different type of ThreadPools catering to specific need. public static ExecutorService newSingleThreadExecutor() Creates an Executor that uses a single worker thread operating off an unbounded queue There is a difference between newFixedThreadPool(1) and newSingleThreadE...
Thread Pools are used mostly calling methods in ExecutorService. The following methods can be used to submit work for execution: MethodDescriptionsubmitExecutes a the submitted work and return a future which can be used to get the resultexecuteExecute the task sometime in the future without gettin...

Page 1 of 1