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