Java Reference
In-Depth Information
This approach feels backward to me, but it's not hard to use. The first argument is the
selector the channel is registering with. The second argument is a named constant from
the
SelectionKey
class identifying the operation the channel is registering for. The
SelectionKey
class defines four named bit constants used to select the type of the op‐
eration:
•
SelectionKey.OP_ACCEPT
•
SelectionKey.OP_CONNECT
•
SelectionKey.OP_READ
•
SelectionKey.OP_WRITE
These are bit-flag int constants (1, 2, 4, etc.). Therefore, if a channel needs to register
for multiple operations in the same selector (e.g., for both reading and writing on a
socket), combine the constants with the bitwise or operator (
|
) when registering:
channel
.
register
(
selector
,
SelectionKey
.
OP_READ
|
SelectionKey
.
OP_WRITE
);
The optional third argument is an attachment for the key. This object is often used to
store state for the connection. For example, if you were implementing a web server, you
might attach a
FileInputStream
or
FileChannel
connected to the local file the server
streams to the client.
After the different channels have been registered with the selector, you can query the
selector at any time to find out which channels are ready to be processed. Channels may
be ready for some operations and not others. For instance, a channel could be ready for
reading but not writing.
There are three methods that select the ready channels. They differ in how long they
wait to find a ready channel. The first,
selectNow()
, performs a nonblocking select. It
returns immediately if no connections are ready to be processed now:
public
abstract
int
selectNow
()
throws
IOException
The other two select methods are blocking:
public
abstract
int
select
()
throws
IOException
public
abstract
int
select
(
long
timeout
)
throws
IOException
The first method waits until at least one registered channel is ready to be processed
before returning. The second waits no longer than
timeout
milliseconds for a channel
to be ready before returning 0. These methods are useful if your program doesn't have
anything to do when no channels are ready to be processed.
When you know the channels are ready to be processed, retrieve the ready channels
using
selectedKeys()
:
public
abstract
Set
<
SelectionKey
>
selectedKeys
()