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 true} if, and only if, this 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      * Retrieves this key's ready-operation set.
 194      *
 195      * <p> It is guaranteed that the returned set will only contain operation
 196      * bits that are valid for this key's channel.  </p>
 197      *
 198      * @return  This key's ready-operation set
 199      *
 200      * @throws  CancelledKeyException
 201      *          If this key has been cancelled
 202      */
 203     public abstract int readyOps();
 204 
 205 
 206     // -- Operation bits and bit-testing convenience methods --
 207 
 208     /**
 209      * Operation-set bit for read operations.
 210      *
 211      * <p> Suppose that a selection key's interest set contains
 212      * {@code OP_READ} at the start of a <a
 213      * href="Selector.html#selop">selection operation</a>.  If the selector
 214      * detects that the corresponding channel is ready for reading, has reached
 215      * end-of-stream, has been remotely shut down for further reading, or has
 216      * an error pending, then it will add {@code OP_READ} to the key's
 217      * ready-operation set and add the key to its selected-key&nbsp;set.  </p>
 218      */
 219     public static final int OP_READ = 1 << 0;
 220 
 221     /**
 222      * Operation-set bit for write operations.
 223      *
 224      * <p> Suppose that a selection key's interest set contains
 225      * {@code OP_WRITE} at the start of a <a
 226      * href="Selector.html#selop">selection operation</a>.  If the selector
 227      * detects that the corresponding channel is ready for writing, has been
 228      * remotely shut down for further writing, or has an error pending, then it
 229      * will add {@code OP_WRITE} to the key's ready set and add the key to its
 230      * selected-key&nbsp;set.  </p>
 231      */
 232     public static final int OP_WRITE = 1 << 2;
 233 
 234     /**
 235      * Operation-set bit for socket-connect operations.
 236      *
 237      * <p> Suppose that a selection key's interest set contains
 238      * {@code OP_CONNECT} at the start of a <a
 239      * href="Selector.html#selop">selection operation</a>.  If the selector
 240      * detects that the corresponding socket channel is ready to complete its
 241      * connection sequence, or has an error pending, then it will add
 242      * {@code OP_CONNECT} to the key's ready set and add the key to its
 243      * selected-key&nbsp;set.  </p>
 244      */
 245     public static final int OP_CONNECT = 1 << 3;
 246 
 247     /**
 248      * Operation-set bit for socket-accept operations.
 249      *
 250      * <p> Suppose that a selection key's interest set contains
 251      * {@code OP_ACCEPT} at the start of a <a
 252      * href="Selector.html#selop">selection operation</a>.  If the selector
 253      * detects that the corresponding server-socket channel is ready to accept
 254      * another connection, or has an error pending, then it will add
 255      * {@code OP_ACCEPT} to the key's ready set and add the key to its
 256      * selected-key&nbsp;set.  </p>
 257      */
 258     public static final int OP_ACCEPT = 1 << 4;
 259 
 260     /**
 261      * Tests whether this key's channel is ready for reading.
 262      *
 263      * <p> An invocation of this method of the form {@code k.isReadable()}
 264      * behaves in exactly the same way as the expression
 265      *
 266      * <blockquote><pre>{@code
 267      * k.readyOps() & OP_READ != 0
 268      * }</pre></blockquote>
 269      *
 270      * <p> If this key's channel does not support read operations then this
 271      * method always returns {@code false}.  </p>
 272      *
 273      * @return  {@code true} if, and only if,
 274                 {@code readyOps() & OP_READ} is nonzero
 275      *
 276      * @throws  CancelledKeyException
 277      *          If this key has been cancelled
 278      */
 279     public final boolean isReadable() {
 280         return (readyOps() & OP_READ) != 0;
 281     }
 282 
 283     /**
 284      * Tests whether this key's channel is ready for writing.
 285      *
 286      * <p> An invocation of this method of the form {@code k.isWritable()}
 287      * behaves in exactly the same way as the expression
 288      *
 289      * <blockquote><pre>{@code
 290      * k.readyOps() & OP_WRITE != 0
 291      * }</pre></blockquote>
 292      *
 293      * <p> If this key's channel does not support write operations then this
 294      * method always returns {@code false}.  </p>
 295      *
 296      * @return  {@code true} if, and only if,
 297      *          {@code readyOps() & OP_WRITE} is nonzero
 298      *
 299      * @throws  CancelledKeyException
 300      *          If this key has been cancelled
 301      */
 302     public final boolean isWritable() {
 303         return (readyOps() & OP_WRITE) != 0;
 304     }
 305 
 306     /**
 307      * Tests whether this key's channel has either finished, or failed to
 308      * finish, its socket-connection operation.
 309      *
 310      * <p> An invocation of this method of the form {@code k.isConnectable()}
 311      * behaves in exactly the same way as the expression
 312      *
 313      * <blockquote><pre>{@code
 314      * k.readyOps() & OP_CONNECT != 0
 315      * }</pre></blockquote>
 316      *
 317      * <p> If this key's channel does not support socket-connect operations
 318      * then this method always returns {@code false}.  </p>
 319      *
 320      * @return  {@code true} if, and only if,
 321      *          {@code readyOps() & OP_CONNECT} is nonzero
 322      *
 323      * @throws  CancelledKeyException
 324      *          If this key has been cancelled
 325      */
 326     public final boolean isConnectable() {
 327         return (readyOps() & OP_CONNECT) != 0;
 328     }
 329 
 330     /**
 331      * Tests whether this key's channel is ready to accept a new socket
 332      * connection.
 333      *
 334      * <p> An invocation of this method of the form {@code k.isAcceptable()}
 335      * behaves in exactly the same way as the expression
 336      *
 337      * <blockquote><pre>{@code
 338      * k.readyOps() & OP_ACCEPT != 0
 339      * }</pre></blockquote>
 340      *
 341      * <p> If this key's channel does not support socket-accept operations then
 342      * this method always returns {@code false}.  </p>
 343      *
 344      * @return  {@code true} if, and only if,
 345      *          {@code readyOps() & OP_ACCEPT} is nonzero
 346      *
 347      * @throws  CancelledKeyException
 348      *          If this key has been cancelled
 349      */
 350     public final boolean isAcceptable() {
 351         return (readyOps() & OP_ACCEPT) != 0;
 352     }
 353 
 354 
 355     // -- Attachments --
 356 
 357     private volatile Object attachment;
 358 
 359     private static final AtomicReferenceFieldUpdater<SelectionKey,Object>
 360         attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(
 361             SelectionKey.class, Object.class, "attachment"
 362         );
 363 
 364     /**
 365      * Attaches the given object to this key.
 366      *
 367      * <p> An attached object may later be retrieved via the {@link #attachment()
 368      * attachment} method.  Only one object may be attached at a time; invoking
 369      * this method causes any previous attachment to be discarded.  The current
 370      * attachment may be discarded by attaching {@code null}.  </p>
 371      *
 372      * @param  ob
 373      *         The object to be attached; may be {@code null}
 374      *
 375      * @return  The previously-attached object, if any,
 376      *          otherwise {@code null}
 377      */
 378     public final Object attach(Object ob) {
 379         return attachmentUpdater.getAndSet(this, ob);
 380     }
 381 
 382     /**
 383      * Retrieves the current attachment.
 384      *
 385      * @return  The object currently attached to this key,
 386      *          or {@code null} if there is no attachment
 387      */
 388     public final Object attachment() {
 389         return attachment;
 390     }
 391 
 392 }