nio2

Thread Pool Strategies

 

non-blocking synchronous I/O 与 non-blocking asynchronous I/O的区别?

 

Using CompletionHandler
class Connection { … }
class Handler implements CompletionHandler<Integer,Connection> {
public void completed(Integer result, Connection conn) {
int nread = result;
// handle result
}
public void failed(Throwable exc, Connection conn) {
// error handling
}
}

 

Groups
> What threads invoke the completion handlers?

Network oriented channels bound to a group
– AsynchronousChannelGroup

Completion handlers invoked by pooled threads

 

Creating a group
// fixed thread pool
ThreadFactory myThreadFactory = …
int nthreads = …
AsynchronousChannelGroup group = AsynchronousChannelGroup
.withFixedThreadPool(nThreads, threadFactory);

 

Creating a group
// custom thread pool
ExecutorService pool = ...
AsynchronousChannelGroup group = AsynchronousChannelGroup
.withThreadPool(pool);

 

Creating a group
// custom thread pool
ExecutorService pool = ...
AsynchronousChannelGroup group = AsynchronousChannelGroup
.withThreadPool(pool);
AsynchronousSocketChannel channel =
AsynchronousSocketChannel.open(group);

 

Thread pools
> Fixed thread pool
– Each thread waits on I/O event
– do I/O completion
– invoke completion handler
– go back to waiting for I/O events
> Cached or custom thread pool
– Internal threads wait on I/O events
– Submit tasks to thread pool to dispatch to
completion handler

 

Fixed Thread Pool与Cached Thread Pool的区别?

 

Termination of CompletionHandlers due to uncaught error or runtime
exception causes pooled thread to exit

 

ByteBuffers
> Not safe for use by multiple concurrent threads
> When I/O operation is initiated then must take
great care not to access buffer until I/O
operation completes

 

Asynchronous close
● Causes all outstanding I/O operations to fail

 

Cancellation
● Future interface defines cancel method
● Forceful cancel allows to close channel

 

With AIO, you can configure the thread pool
(ExecutorService) used by both the AIO kernel
and your application
AsynchronousChannelGroup.withCachedThreadPool
(ExecutorService, initialSize)
AsynchronousChannelGroup.withThreadPool
(ExecutorService)
AsynchronousChannelGroup.withFixedThreadPool
(nThread, ThreadFactory)
…or use the preconfigured/built in Thread Pool that
comes by default…

 

you just win a prize: a thread's context switch
for free!!

 

For CachedThreadPool!

Possibility of OOM if the queue grow
indefinitively => monitor the queue

 

ByteBuffer pool

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值