how to register multiple SocketChannel on one thread with a Selector on different thread

628 views Asked by At

I am developing an Android app in which I am using SocketChannel with Selector for sending network requests to my server.

I have a selector on one threads which has registered for OP_CONNECT, OP_WRITE and OP_READ and which calls the select() method to receive these events.

can anybody suggest me correct way of doing the multi-threaded registration of SocketChannel with a single Selector ?

1

There are 1 answers

0
Alex Suo On

The time-consuming part is the actual read from/write to the channels. So basically you would

  1. Set up a set of socket channels
  2. Register all them to a selector.
  3. In your main selection thread call select(). Once return value > 0, get the set of selection keys and determine if you want to read/write on the associated channels.
  4. Create a thread pool. Do all your actual read/write to the channels by that pool. Or even, cache your Runnable instances if you want zero object loop.