Java Notes-7

-One such related pair of patterns is the concept
of an executor service that manages tasks and that of a thread pool that services tasks in

an efficient way.

技术分享

-The new  Callable interface, which is effectively
a replacement for  Runnable , rectifies this situation by providing a  call() method that
both returns a result and can throw exceptions. 

技术分享

-The new  Future class is used with  Callable and serves as a handle to wait for and
retrieve the result of the task or cancel the task before it is executed. 

技术分享

-By
contrast, an  ExecutorService is intended to be an asynchronous task handler. Instead
of an  execute() method, it has  submit() methods that accept a  Callable (or  Runna
ble ) and return immediately with a  Future object that can be used to manage the task
and collect the result later

-newFixedThreadPool(int)
This is the classic thread pool with a specified maximum pool size and an unboun‐
ded queue for task submission. If a thread dies for some reason while handling a
task, a new one will be created to replace it. Threads are never removed from the
pool until the service is shut down.
newCachedThreadPool()
This pool uses an open-ended number of threads that grows and shrinks with de‐
mand. The main advantage of this service is that threads are cached for a period of
time and reused, eliminating the overhead of creating new threads for short-lived
tasks. Threads that are not used for one minute are removed. Tasks are submitted
directly to threads; there is no real queuing.
newSingleThreadExecutor()
This  ExecutorService uses a single thread to execute tasks from an unbounded
queue. In this sense, it is identical to a fixed thread pool with a pool size of  1 

技术分享

-In addition to its individual task  submit() methods,  ExecutorService also offers a set
of collective  invokeAll() and  invokeAny() executor methods that submit multiple
tasks as a group and return results either when they are all complete or when the first
one completes, respectively. 

技术分享

-A  CompletionService is a lightweight queue-like frontend to an executor. The  Comple
tionService provides  submit() methods, which delegate their tasks to a particular
instance of  Executor , and then provides  take() and  poll() methods for retrieving
Future results for completed tasks.

技术分享

-The Fork/Join framework is a new API added in Java 7 that provides just this—a way
for you to structure your tasks so that they can be split up as needed to keep all of the
available threads busy working on data with as much continuity as possible. 

-The framework then
implements what is known as a “work stealing” algorithm, allowing threads that are free
to grab unstarted tasks from their neighbors’ queues.


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。