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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值