nio2

    技术2022-05-19  18

    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


    最新回复(0)