1/*
2 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.nio.channels;
27
28import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
29
30/**
31 * A token representing the registration of a {@link SelectableChannel} with a
32 * {@link Selector}.
33 *
34 * <p> A selection key is created each time a channel is registered with a
35 * selector.  A key remains valid until it is <i>cancelled</i> by invoking its
36 * {@link #cancel cancel} method, by closing its channel, or by closing its
37 * selector.  Cancelling a key does not immediately remove it from its
38 * selector; it is instead added to the selector's <a
39 * href="Selector.html#ks"><i>cancelled-key set</i></a> for removal during the
40 * next selection operation.  The validity of a key may be tested by invoking
41 * its {@link #isValid isValid} method.
42 *
43 * <a id="opsets"></a>
44 *
45 * <p> A selection key contains two <i>operation sets</i> represented as
46 * integer values.  Each bit of an operation set denotes a category of
47 * selectable operations that are supported by the key's channel.
48 *
49 * <ul>
50 *
51 *   <li><p> The <i>interest set</i> determines which operation categories will
52 *   be tested for readiness the next time one of the selector's selection
53 *   methods is invoked.  The interest set is initialized with the value given
54 *   when the key is created; it may later be changed via the {@link
55 *   #interestOps(int)} method. </p></li>
56 *
57 *   <li><p> The <i>ready set</i> identifies the operation categories for which
58 *   the key's channel has been detected to be ready by the key's selector.
59 *   The ready set is initialized to zero when the key is created; it may later
60 *   be updated by the selector during a selection operation, but it cannot be
61 *   updated directly. </p></li>
62 *
63 * </ul>
64 *
65 * <p> That a selection key's ready set indicates that its channel is ready for
66 * some operation category is a hint, but not a guarantee, that an operation in
67 * such a category may be performed by a thread without causing the thread to
68 * block.  A ready set is most likely to be accurate immediately after the
69 * completion of a selection operation.  It is likely to be made inaccurate by
70 * external events and by I/O operations that are invoked upon the
71 * corresponding channel.
72 *
73 * <p> This class defines all known operation-set bits, but precisely which
74 * bits are supported by a given channel depends upon the type of the channel.
75 * Each subclass of {@link SelectableChannel} defines an {@link
76 * SelectableChannel#validOps() validOps()} method which returns a set
77 * identifying just those operations that are supported by the channel.  An
78 * attempt to set or test an operation-set bit that is not supported by a key's
79 * channel will result in an appropriate run-time exception.
80 *
81 * <p> It is often necessary to associate some application-specific data with a
82 * selection key, for example an object that represents the state of a
83 * higher-level protocol and handles readiness notifications in order to
84 * implement that protocol.  Selection keys therefore support the
85 * <i>attachment</i> of a single arbitrary object to a key.  An object can be
86 * attached via the {@link #attach attach} method and then later retrieved via
87 * the {@link #attachment() attachment} method.
88 *
89 * <p> Selection keys are safe for use by multiple concurrent threads.  The
90 * operations of reading and writing the interest set will, in general, be
91 * synchronized with certain operations of the selector.  Exactly how this
92 * synchronization is performed is implementation-dependent: In a naive
93 * implementation, reading or writing the interest set may block indefinitely
94 * if a selection operation is already in progress; in a high-performance
95 * implementation, reading or writing the interest set may block briefly, if at
96 * all.  In any case, a selection operation will always use the interest-set
97 * value that was current at the moment that the operation began.  </p>
98 *
99 *
100 * @author Mark Reinhold
101 * @author JSR-51 Expert Group
102 * @since 1.4
103 *
104 * @see SelectableChannel
105 * @see Selector
106 */
107
108public abstract class SelectionKey {
109
110    /**
111     * Constructs an instance of this class.
112     */
113    protected SelectionKey() { }
114
115
116    // -- Channel and selector operations --
117
118    /**
119     * Returns the channel for which this key was created.  This method will
120     * continue to return the channel even after the key is cancelled.
121     *
122     * @return  This key's channel
123     */
124    public abstract SelectableChannel channel();
125
126    /**
127     * Returns the selector for which this key was created.  This method will
128     * continue to return the selector even after the key is cancelled.
129     *
130     * @return  This key's selector
131     */
132    public abstract Selector selector();
133
134    /**
135     * Tells whether or not this key is valid.
136     *
137     * <p> A key is valid upon creation and remains so until it is cancelled,
138     * its channel is closed, or its selector is closed.  </p>
139     *
140     * @return  {@code true} if, and only if, this key is valid
141     */
142    public abstract boolean isValid();
143
144    /**
145     * Requests that the registration of this key's channel with its selector
146     * be cancelled.  Upon return the key will be invalid and will have been
147     * added to its selector's cancelled-key set.  The key will be removed from
148     * all of the selector's key sets during the next selection operation.
149     *
150     * <p> If this key has already been cancelled then invoking this method has
151     * no effect.  Once cancelled, a key remains forever invalid. </p>
152     *
153     * <p> This method may be invoked at any time.  It synchronizes on the
154     * selector's cancelled-key set, and therefore may block briefly if invoked
155     * concurrently with a cancellation or selection operation involving the
156     * same selector.  </p>
157     */
158    public abstract void cancel();
159
160
161    // -- Operation-set accessors --
162
163    /**
164     * Retrieves this key's interest set.
165     *
166     * <p> It is guaranteed that the returned set will only contain operation
167     * bits that are valid for this key's channel.
168     *
169     * <p> This method may be invoked at any time.  Whether or not it blocks,
170     * and for how long, is implementation-dependent.  </p>
171     *
172     * @return  This key's interest set
173     *
174     * @throws  CancelledKeyException
175     *          If this key has been cancelled
176     */
177    public abstract int interestOps();
178
179    /**
180     * Sets this key's interest set to the given value.
181     *
182     * <p> This method may be invoked at any time.  Whether or not it blocks,
183     * and for how long, is implementation-dependent.  </p>
184     *
185     * @param  ops  The new interest set
186     *
187     * @return  This selection key
188     *
189     * @throws  IllegalArgumentException
190     *          If a bit in the set does not correspond to an operation that
191     *          is supported by this key's channel, that is, if
192     *          {@code (ops & ~channel().validOps()) != 0}
193     *
194     * @throws  CancelledKeyException
195     *          If this key has been cancelled
196     */
197    public abstract SelectionKey interestOps(int ops);
198
199    /**
200     * Retrieves this key's ready-operation set.
201     *
202     * <p> It is guaranteed that the returned set will only contain operation
203     * bits that are valid for this key's channel.  </p>
204     *
205     * @return  This key's ready-operation set
206     *
207     * @throws  CancelledKeyException
208     *          If this key has been cancelled
209     */
210    public abstract int readyOps();
211
212
213    // -- Operation bits and bit-testing convenience methods --
214
215    /**
216     * Operation-set bit for read operations.
217     *
218     * <p> Suppose that a selection key's interest set contains
219     * {@code OP_READ} at the start of a <a
220     * href="Selector.html#selop">selection operation</a>.  If the selector
221     * detects that the corresponding channel is ready for reading, has reached
222     * end-of-stream, has been remotely shut down for further reading, or has
223     * an error pending, then it will add {@code OP_READ} to the key's
224     * ready-operation set and add the key to its selected-key&nbsp;set.  </p>
225     */
226    public static final int OP_READ = 1 << 0;
227
228    /**
229     * Operation-set bit for write operations.
230     *
231     * <p> Suppose that a selection key's interest set contains
232     * {@code OP_WRITE} at the start of a <a
233     * href="Selector.html#selop">selection operation</a>.  If the selector
234     * detects that the corresponding channel is ready for writing, has been
235     * remotely shut down for further writing, or has an error pending, then it
236     * will add {@code OP_WRITE} to the key's ready set and add the key to its
237     * selected-key&nbsp;set.  </p>
238     */
239    public static final int OP_WRITE = 1 << 2;
240
241    /**
242     * Operation-set bit for socket-connect operations.
243     *
244     * <p> Suppose that a selection key's interest set contains
245     * {@code OP_CONNECT} at the start of a <a
246     * href="Selector.html#selop">selection operation</a>.  If the selector
247     * detects that the corresponding socket channel is ready to complete its
248     * connection sequence, or has an error pending, then it will add
249     * {@code OP_CONNECT} to the key's ready set and add the key to its
250     * selected-key&nbsp;set.  </p>
251     */
252    public static final int OP_CONNECT = 1 << 3;
253
254    /**
255     * Operation-set bit for socket-accept operations.
256     *
257     * <p> Suppose that a selection key's interest set contains
258     * {@code OP_ACCEPT} at the start of a <a
259     * href="Selector.html#selop">selection operation</a>.  If the selector
260     * detects that the corresponding server-socket channel is ready to accept
261     * another connection, or has an error pending, then it will add
262     * {@code OP_ACCEPT} to the key's ready set and add the key to its
263     * selected-key&nbsp;set.  </p>
264     */
265    public static final int OP_ACCEPT = 1 << 4;
266
267    /**
268     * Tests whether this key's channel is ready for reading.
269     *
270     * <p> An invocation of this method of the form {@code k.isReadable()}
271     * behaves in exactly the same way as the expression
272     *
273     * <blockquote><pre>{@code
274     * k.readyOps() & OP_READ != 0
275     * }</pre></blockquote>
276     *
277     * <p> If this key's channel does not support read operations then this
278     * method always returns {@code false}.  </p>
279     *
280     * @return  {@code true} if, and only if,
281                {@code readyOps() & OP_READ} is nonzero
282     *
283     * @throws  CancelledKeyException
284     *          If this key has been cancelled
285     */
286    public final boolean isReadable() {
287        return (readyOps() & OP_READ) != 0;
288    }
289
290    /**
291     * Tests whether this key's channel is ready for writing.
292     *
293     * <p> An invocation of this method of the form {@code k.isWritable()}
294     * behaves in exactly the same way as the expression
295     *
296     * <blockquote><pre>{@code
297     * k.readyOps() & OP_WRITE != 0
298     * }</pre></blockquote>
299     *
300     * <p> If this key's channel does not support write operations then this
301     * method always returns {@code false}.  </p>
302     *
303     * @return  {@code true} if, and only if,
304     *          {@code readyOps() & OP_WRITE} is nonzero
305     *
306     * @throws  CancelledKeyException
307     *          If this key has been cancelled
308     */
309    public final boolean isWritable() {
310        return (readyOps() & OP_WRITE) != 0;
311    }
312
313    /**
314     * Tests whether this key's channel has either finished, or failed to
315     * finish, its socket-connection operation.
316     *
317     * <p> An invocation of this method of the form {@code k.isConnectable()}
318     * behaves in exactly the same way as the expression
319     *
320     * <blockquote><pre>{@code
321     * k.readyOps() & OP_CONNECT != 0
322     * }</pre></blockquote>
323     *
324     * <p> If this key's channel does not support socket-connect operations
325     * then this method always returns {@code false}.  </p>
326     *
327     * @return  {@code true} if, and only if,
328     *          {@code readyOps() & OP_CONNECT} is nonzero
329     *
330     * @throws  CancelledKeyException
331     *          If this key has been cancelled
332     */
333    public final boolean isConnectable() {
334        return (readyOps() & OP_CONNECT) != 0;
335    }
336
337    /**
338     * Tests whether this key's channel is ready to accept a new socket
339     * connection.
340     *
341     * <p> An invocation of this method of the form {@code k.isAcceptable()}
342     * behaves in exactly the same way as the expression
343     *
344     * <blockquote><pre>{@code
345     * k.readyOps() & OP_ACCEPT != 0
346     * }</pre></blockquote>
347     *
348     * <p> If this key's channel does not support socket-accept operations then
349     * this method always returns {@code false}.  </p>
350     *
351     * @return  {@code true} if, and only if,
352     *          {@code readyOps() & OP_ACCEPT} is nonzero
353     *
354     * @throws  CancelledKeyException
355     *          If this key has been cancelled
356     */
357    public final boolean isAcceptable() {
358        return (readyOps() & OP_ACCEPT) != 0;
359    }
360
361
362    // -- Attachments --
363
364    private volatile Object attachment;
365
366    private static final AtomicReferenceFieldUpdater<SelectionKey,Object>
367        attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(
368            SelectionKey.class, Object.class, "attachment"
369        );
370
371    /**
372     * Attaches the given object to this key.
373     *
374     * <p> An attached object may later be retrieved via the {@link #attachment()
375     * attachment} method.  Only one object may be attached at a time; invoking
376     * this method causes any previous attachment to be discarded.  The current
377     * attachment may be discarded by attaching {@code null}.  </p>
378     *
379     * @param  ob
380     *         The object to be attached; may be {@code null}
381     *
382     * @return  The previously-attached object, if any,
383     *          otherwise {@code null}
384     */
385    public final Object attach(Object ob) {
386        return attachmentUpdater.getAndSet(this, ob);
387    }
388
389    /**
390     * Retrieves the current attachment.
391     *
392     * @return  The object currently attached to this key,
393     *          or {@code null} if there is no attachment
394     */
395    public final Object attachment() {
396        return attachment;
397    }
398
399}
400