Java Reference
In-Depth Information
You iterate through the returned set, processing each
SelectionKey
in turn. You'll also
want to remove the key from the iterator to tell the selector that you've handled it.
Otherwise, the selector will keep telling you about it on future passes through the loop.
Finally, when you're ready to shut down the server or when you no longer need the
selector, you should close it:
public
abstract
void
close
()
throws
IOException
This step releases any resources associated with the selector. More importantly, it cancels
all keys registered with the selector and interrupts up any threads blocked by one of this
selector's select methods.
The SelectionKey Class
SelectionKey
objects serve as pointers to channels. They can also hold an object at‐
tachment, which is how you normally store the state for the connection on that channel.
SelectionKey
objects are returned by the
register()
method when registering a
channel with a selector. However, you don't usually need to retain this reference. The
selectedKeys()
method returns the same objects again inside a
Set
. A single channel
can be registered with multiple selectors.
When retrieving a
SelectionKey
from the set of selected keys, you often first test what
that key is ready to do. There are four possibilities:
public
final
boolean
isAcceptable
()
public
final
boolean
isConnectable
()
public
final
boolean
isReadable
()
public
final
boolean
isWritable
()
This test isn't always necessary. In some cases, the selector is only testing for one pos‐
sibility and will only return keys to do that one thing. But if the selector does test for
multiple readiness states, you'll want to test which one kicked the channel into the ready
state before operating on it. It's also possible that a channel is ready to do more than one
thing.
Once you know what the channel associated with the key is ready to do, retrieve the
channel with the
channel()
method:
public
abstract
SelectableChannel
channel
()
If you've stored an object in the
SelectionKey
to hold state information, you can retrieve
it with the
attachment()
method:
public
final
Object
attachment
()
Finally, when you're finished with a connection, deregister its
SelectionKey
object so
the selector doesn't waste any resources querying it for readiness. I don't know that this