This is part 4 of my notes from reading Java Concurrency in Practice.
NOTE: These summaries are NOT meant to replace the book. I highly recommend buying your own copy of the book if you haven't already read it.
Chapter 6 - Task Execution
- Individual client requests are a natural task boundary choice for server applications.
- Creating a new thread per task is usually NOT a good idea.
- Overheads of thread creation and teardown can add up to be quite significant.
- Active threads consume system resources like memory even when they are idle, and also increase CPU contention.
- Creating too many threads can result in an OutOfMemoryError.
- Primary abstraction for task execution in Java is the Executor framework, not Threads.
- Executor interface has a void execute(Runnable) methods.
- Executors are the easiest way to implement a producer-consumer design.
- Decouples task submission from execution. Execution policy is separated from task submission.
- Always use Executor instead of new Thread(runnable).start()
- Different types of Thread Pools can be created using static factory methods of the Executors class:
- newFixedThreadPool - creates new threads upto a maximum specified size. Tries to keep pool size constant by adding new threads if some die due to exceptions.
- newCachedThreadPool - No bounds on number of threads. Number of threads increase/decrease based on load.
- newSingleThreadExecutor - Used to process tasks sequentially in order imposed by task queue (FIFO, LIFO, priority order). Replaces thread if it dies unexpectedly.
- newScheduledThreadPool - Fixed size thread pool that supports delayed and periodic task execution.
- Use instead of Timer.
- Timer creates only a single thread. If one task takes too long, it affects the timing accuracy of subsequent TimerTasks.
- An unchecked exception thrown by a TimerTask terminates the Timer thread. The Timer thread is not resurrected, and the Timer is simply cancelled.
- Scheduled thread pools do not have the above two limitations However, Timers can schedule based on absolute time, while scheduled thread pools only support relative time.
- Executor lifecycle has 3 states - running, shutting down, terminated.
- ExecutorService interface (that extends Executor) offers methods like shutdown(), shutdownNow(), isShutdown(), isTerminated(), awaitTermination() to control Executor life cycle.
- shutdown() - graceful shutdown. Allow all running and previously submitted tasks to complete. No new tasks are accepted.
- shutdownNow() - cancel running tasks, and ignores any queued tasks.
- Tasks submitted to executor after shutdown are passed to a rejection handler, which may silently drop the task or throw a RejectedExecutionException.
- awaitTermination() is usually called immediately after calling shutdown().
- ExecutorService.submit(Callable) returns a Future. A Future represents the lifecycle of a task, and provides methods to monitor/control it.
- CompletionService combines the functionality of an Executor and a BlockingQueue. Submit a bunch of Callables to the Executor, and then wait for the results to be available using take() and poll().
- An ExecutorCompletionService is a wrapper around an Executor - new ExecutorCompletionService
(executor). - Tasks are submitted to the completion service, and not directly to the Executor.
- Multiple completion services can share an Executor.
- Keep track of the number of tasks submitted in order to determine the number of times to call take().
- Future.get() supports a version that throws a TimeoutException if the result is not available within the specified time delay.
- If a TimeoutException happens, then call cancel on the Future to cancel the task. If the task is written to be cancelable, then it can be terminated to avoid consuming unnecessary resources.
- ExecutorService.invokeAll - takes a collection of tasks and returns a collection of Futures. Timed version of invokeAll returns when all tasks have completed, the calling thread is interrupted or if the timeout expires. Use Future.isCancelled() to determine if a particular task completed or was interrupted/cancelled.
No comments:
Post a Comment