1 /*
2  * Copyright (c) 2000, 2018, 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
26 package java.nio.channels;
27
28 import 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.  A
90  * selection operation will always use the interest-set value that was current
91  * at the moment that the operation began.  </p>
92  *
93  *
94  * @author Mark Reinhold
95  * @author JSR-51 Expert Group
96  * @since 1.4
97  *
98  * @see SelectableChannel
99  * @see Selector
100  */

101
102 public abstract class SelectionKey {
103
104     /**
105      * Constructs an instance of this class.
106      */

107     protected SelectionKey() { }
108
109
110     // -- Channel and selector operations --
111
112     /**
113      * Returns the channel for which this key was created.  This method will
114      * continue to return the channel even after the key is cancelled.
115      *
116      * @return  This key's channel
117      */

118     public abstract SelectableChannel channel();
119
120     /**
121      * Returns the selector for which this key was created.  This method will
122      * continue to return the selector even after the key is cancelled.
123      *
124      * @return  This key's selector
125      */

126     public abstract Selector selector();
127
128     /**
129      * Tells whether or not this key is valid.
130      *
131      * <p> A key is valid upon creation and remains so until it is cancelled,
132      * its channel is closed, or its selector is closed.  </p>
133      *
134      * @return  {@code trueif, and only ifthis key is valid
135      */

136     public abstract boolean isValid();
137
138     /**
139      * Requests that the registration of this key's channel with its selector
140      * be cancelled.  Upon return the key will be invalid and will have been
141      * added to its selector's cancelled-key set.  The key will be removed from
142      * all of the selector's key sets during the next selection operation.
143      *
144      * <p> If this key has already been cancelled then invoking this method has
145      * no effect.  Once cancelled, a key remains forever invalid. </p>
146      *
147      * <p> This method may be invoked at any time.  It synchronizes on the
148      * selector's cancelled-key set, and therefore may block briefly if invoked
149      * concurrently with a cancellation or selection operation involving the
150      * same selector.  </p>
151      */

152     public abstract void cancel();
153
154
155     // -- Operation-set accessors --
156
157     /**
158      * Retrieves this key's interest set.
159      *
160      * <p> It is guaranteed that the returned set will only contain operation
161      * bits that are valid for this key's channel. </p>
162      *
163      * @return  This key's interest set
164      *
165      * @throws  CancelledKeyException
166      *          If this key has been cancelled
167      */

168     public abstract int interestOps();
169
170     /**
171      * Sets this key's interest set to the given value.
172      *
173      * <p> This method may be invoked at any time.  If this method is invoked
174      * while a selection operation is in progress then it has no effect upon
175      * that operation; the change to the key's interest set will be seen by the
176      * next selection operation.
177      *
178      * @param  ops  The new interest set
179      *
180      * @return  This selection key
181      *
182      * @throws  IllegalArgumentException
183      *          If a bit in the set does not correspond to an operation that
184      *          is supported by this key's channel, that is, if
185      *          {@code (ops & ~channel().validOps()) != 0}
186      *
187      * @throws  CancelledKeyException
188      *          If this key has been cancelled
189      */

190     public abstract SelectionKey interestOps(int ops);
191
192     /**
193      * Atomically sets this key's interest set to the bitwise union ("or") of
194      * the existing interest set and the given value. This method is guaranteed
195      * to be atomic with respect to other concurrent calls to this method or to
196      * {@link #interestOpsAnd(int)}.
197      *
198      * <p> This method may be invoked at any time.  If this method is invoked
199      * while a selection operation is in progress then it has no effect upon
200      * that operation; the change to the key's interest set will be seen by the
201      * next selection operation.
202      *
203      * @implSpec The default implementation synchronizes on this key and invokes
204      * {@code interestOps()} and {@code interestOps(int)} to retrieve and set
205      * this key's interest set.
206      *
207      * @param  ops  The interest set to apply
208      *
209      * @return  The previous interest set
210      *
211      * @throws  IllegalArgumentException
212      *          If a bit in the set does not correspond to an operation that
213      *          is supported by this key's channel, that is, if
214      *          {@code (ops & ~channel().validOps()) != 0}
215      *
216      * @throws  CancelledKeyException
217      *          If this key has been cancelled
218      *
219      * @since 11
220      */

221     public int interestOpsOr(int ops) {
222         synchronized (this) {
223             int oldVal = interestOps();
224             interestOps(oldVal | ops);
225             return oldVal;
226         }
227     }
228
229     /**
230      * Atomically sets this key's interest set to the bitwise intersection ("and")
231      * of the existing interest set and the given value. This method is guaranteed
232      * to be atomic with respect to other concurrent calls to this method or to
233      * {@link #interestOpsOr(int)}.
234      *
235      * <p> This method may be invoked at any time.  If this method is invoked
236      * while a selection operation is in progress then it has no effect upon
237      * that operation; the change to the key's interest set will be seen by the
238      * next selection operation.
239      *
240      * @apiNote Unlike the {@code interestOps(int)} and {@code interestOpsOr(int)}
241      * methods, this method does not throw {@code IllegalArgumentException} when
242      * invoked with bits in the interest set that do not correspond to an
243      * operation that is supported by this key's channel. This is to allow
244      * operation bits in the interest set to be cleared using bitwise complement
245      * values, e.g., {@code interestOpsAnd(~SelectionKey.OP_READ)} will remove
246      * the {@code OP_READ} from the interest set without affecting other bits.
247      *
248      * @implSpec The default implementation synchronizes on this key and invokes
249      * {@code interestOps()} and {@code interestOps(int)} to retrieve and set
250      * this key's interest set.
251      *
252      * @param  ops  The interest set to apply
253      *
254      * @return  The previous interest set
255      *
256      * @throws  CancelledKeyException
257      *          If this key has been cancelled
258      *
259      * @since 11
260      */

261     public int interestOpsAnd(int ops) {
262         synchronized (this) {
263             int oldVal = interestOps();
264             interestOps(oldVal & ops);
265             return oldVal;
266         }
267     }
268
269     /**
270      * Retrieves this key's ready-operation set.
271      *
272      * <p> It is guaranteed that the returned set will only contain operation
273      * bits that are valid for this key's channel.  </p>
274      *
275      * @return  This key's ready-operation set
276      *
277      * @throws  CancelledKeyException
278      *          If this key has been cancelled
279      */

280     public abstract int readyOps();
281
282
283     // -- Operation bits and bit-testing convenience methods --
284
285     /**
286      * Operation-set bit for read operations.
287      *
288      * <p> Suppose that a selection key's interest set contains
289      * {@code OP_READ} at the start of a <a
290      * href="Selector.html#selop">selection operation</a>.  If the selector
291      * detects that the corresponding channel is ready for reading, has reached
292      * end-of-stream, has been remotely shut down for further reading, or has
293      * an error pending, then it will add {@code OP_READ} to the key's
294      * ready-operation set.  </p>
295      */

296     public static final int OP_READ = 1 << 0;
297
298     /**
299      * Operation-set bit for write operations.
300      *
301      * <p> Suppose that a selection key's interest set contains
302      * {@code OP_WRITE} at the start of a <a
303      * href="Selector.html#selop">selection operation</a>.  If the selector
304      * detects that the corresponding channel is ready for writing, has been
305      * remotely shut down for further writing, or has an error pending, then it
306      * will add {@code OP_WRITE} to the key's ready set.  </p>
307      */

308     public static final int OP_WRITE = 1 << 2;
309
310     /**
311      * Operation-set bit for socket-connect operations.
312      *
313      * <p> Suppose that a selection key's interest set contains
314      * {@code OP_CONNECT} at the start of a <a
315      * href="Selector.html#selop">selection operation</a>.  If the selector
316      * detects that the corresponding socket channel is ready to complete its
317      * connection sequence, or has an error pending, then it will add
318      * {@code OP_CONNECT} to the key's ready set.  </p>
319      */

320     public static final int OP_CONNECT = 1 << 3;
321
322     /**
323      * Operation-set bit for socket-accept operations.
324      *
325      * <p> Suppose that a selection key's interest set contains
326      * {@code OP_ACCEPT} at the start of a <a
327      * href="Selector.html#selop">selection operation</a>.  If the selector
328      * detects that the corresponding server-socket channel is ready to accept
329      * another connection, or has an error pending, then it will add
330      * {@code OP_ACCEPT} to the key's ready set.  </p>
331      */

332     public static final int OP_ACCEPT = 1 << 4;
333
334     /**
335      * Tests whether this key's channel is ready for reading.
336      *
337      * <p> An invocation of this method of the form {@code k.isReadable()}
338      * behaves in exactly the same way as the expression
339      *
340      * <blockquote><pre>{@code
341      * k.readyOps() & OP_READ != 0
342      * }</pre></blockquote>
343      *
344      * <p> If this key's channel does not support read operations then this
345      * method always returns {@code false}.  </p>
346      *
347      * @return  {@code trueif, and only if,
348                 {@code readyOps() & OP_READ} is nonzero
349      *
350      * @throws  CancelledKeyException
351      *          If this key has been cancelled
352      */

353     public final boolean isReadable() {
354         return (readyOps() & OP_READ) != 0;
355     }
356
357     /**
358      * Tests whether this key's channel is ready for writing.
359      *
360      * <p> An invocation of this method of the form {@code k.isWritable()}
361      * behaves in exactly the same way as the expression
362      *
363      * <blockquote><pre>{@code
364      * k.readyOps() & OP_WRITE != 0
365      * }</pre></blockquote>
366      *
367      * <p> If this key's channel does not support write operations then this
368      * method always returns {@code false}.  </p>
369      *
370      * @return  {@code trueif, and only if,
371      *          {@code readyOps() & OP_WRITE} is nonzero
372      *
373      * @throws  CancelledKeyException
374      *          If this key has been cancelled
375      */

376     public final boolean isWritable() {
377         return (readyOps() & OP_WRITE) != 0;
378     }
379
380     /**
381      * Tests whether this key's channel has either finished, or failed to
382      * finish, its socket-connection operation.
383      *
384      * <p> An invocation of this method of the form {@code k.isConnectable()}
385      * behaves in exactly the same way as the expression
386      *
387      * <blockquote><pre>{@code
388      * k.readyOps() & OP_CONNECT != 0
389      * }</pre></blockquote>
390      *
391      * <p> If this key's channel does not support socket-connect operations
392      * then this method always returns {@code false}.  </p>
393      *
394      * @return  {@code trueif, and only if,
395      *          {@code readyOps() & OP_CONNECT} is nonzero
396      *
397      * @throws  CancelledKeyException
398      *          If this key has been cancelled
399      */

400     public final boolean isConnectable() {
401         return (readyOps() & OP_CONNECT) != 0;
402     }
403
404     /**
405      * Tests whether this key's channel is ready to accept a new socket
406      * connection.
407      *
408      * <p> An invocation of this method of the form {@code k.isAcceptable()}
409      * behaves in exactly the same way as the expression
410      *
411      * <blockquote><pre>{@code
412      * k.readyOps() & OP_ACCEPT != 0
413      * }</pre></blockquote>
414      *
415      * <p> If this key's channel does not support socket-accept operations then
416      * this method always returns {@code false}.  </p>
417      *
418      * @return  {@code trueif, and only if,
419      *          {@code readyOps() & OP_ACCEPT} is nonzero
420      *
421      * @throws  CancelledKeyException
422      *          If this key has been cancelled
423      */

424     public final boolean isAcceptable() {
425         return (readyOps() & OP_ACCEPT) != 0;
426     }
427
428
429     // -- Attachments --
430
431     private volatile Object attachment;
432
433     private static final AtomicReferenceFieldUpdater<SelectionKey,Object>
434         attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(
435             SelectionKey.class, Object.class"attachment"
436         );
437
438     /**
439      * Attaches the given object to this key.
440      *
441      * <p> An attached object may later be retrieved via the {@link #attachment()
442      * attachment} method.  Only one object may be attached at a time; invoking
443      * this method causes any previous attachment to be discarded.  The current
444      * attachment may be discarded by attaching {@code null}.  </p>
445      *
446      * @param  ob
447      *         The object to be attached; may be {@code null}
448      *
449      * @return  The previously-attached object, if any,
450      *          otherwise {@code null}
451      */

452     public final Object attach(Object ob) {
453         return attachmentUpdater.getAndSet(this, ob);
454     }
455
456     /**
457      * Retrieves the current attachment.
458      *
459      * @return  The object currently attached to this key,
460      *          or {@code nullif there is no attachment
461      */

462     public final Object attachment() {
463         return attachment;
464     }
465
466 }
467