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