i’m working with java.nio.channels.Selector and i’d like to create a separate thread for each selectedKey that is ready for read/write/accept but i want to make sure that the same socket is never handled by two different threads simultaneously. what would be the best way to do it ? i was thinking to cancel each selectedKey before creating the thread that’ll handle it’s socket and re-registering the socket to the selector once the thread has finished it’s life but i/m not sure how efficient this will be….
i’m working with java.nio.channels.Selector and i’d like to create a separate thread for each
Share
There’s a really good Doug Lea presentation about Scaleable I/O in Java, which I followed when building my server. I take the following approach:
I have a single I/O thread within my “reactor” that only performs I/O (and very basic decoding / encoding); It simply translates between bytes and message objects and then passes off incoming message objects to a thread pool for business logic processing. I would highly recommend this approach – Unless your I/O thread becomes saturated there is no need for more than one I/O thread, and I would imagine most I/O bottlenecks are because other processing it taking place on this thread.
If you can prove your I/O thread is saturated you could follow the “multiple reactor” pattern suggested in the presentation whereby a master reactor accepts incoming connections and then hands them off to child reactors that perform the procesing. Each child reactor multiplexes between a subset of the total connections, and hence there’s no danger of more than one thread interacting with a given
SelectionKey.