Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/SelectionKey.java
38918 views
/*1* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.channels;2627import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;28import java.io.IOException;293031/**32* A token representing the registration of a {@link SelectableChannel} with a33* {@link Selector}.34*35* <p> A selection key is created each time a channel is registered with a36* selector. A key remains valid until it is <i>cancelled</i> by invoking its37* {@link #cancel cancel} method, by closing its channel, or by closing its38* selector. Cancelling a key does not immediately remove it from its39* selector; it is instead added to the selector's <a40* href="Selector.html#ks"><i>cancelled-key set</i></a> for removal during the41* next selection operation. The validity of a key may be tested by invoking42* its {@link #isValid isValid} method.43*44* <a name="opsets"></a>45*46* <p> A selection key contains two <i>operation sets</i> represented as47* integer values. Each bit of an operation set denotes a category of48* 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 will53* be tested for readiness the next time one of the selector's selection54* methods is invoked. The interest set is initialized with the value given55* when the key is created; it may later be changed via the {@link56* #interestOps(int)} method. </p></li>57*58* <li><p> The <i>ready set</i> identifies the operation categories for which59* 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 later61* be updated by the selector during a selection operation, but it cannot be62* updated directly. </p></li>63*64* </ul>65*66* <p> That a selection key's ready set indicates that its channel is ready for67* some operation category is a hint, but not a guarantee, that an operation in68* such a category may be performed by a thread without causing the thread to69* block. A ready set is most likely to be accurate immediately after the70* completion of a selection operation. It is likely to be made inaccurate by71* external events and by I/O operations that are invoked upon the72* corresponding channel.73*74* <p> This class defines all known operation-set bits, but precisely which75* bits are supported by a given channel depends upon the type of the channel.76* Each subclass of {@link SelectableChannel} defines an {@link77* SelectableChannel#validOps() validOps()} method which returns a set78* identifying just those operations that are supported by the channel. An79* attempt to set or test an operation-set bit that is not supported by a key's80* channel will result in an appropriate run-time exception.81*82* <p> It is often necessary to associate some application-specific data with a83* selection key, for example an object that represents the state of a84* higher-level protocol and handles readiness notifications in order to85* implement that protocol. Selection keys therefore support the86* <i>attachment</i> of a single arbitrary object to a key. An object can be87* attached via the {@link #attach attach} method and then later retrieved via88* the {@link #attachment() attachment} method.89*90* <p> Selection keys are safe for use by multiple concurrent threads. The91* operations of reading and writing the interest set will, in general, be92* synchronized with certain operations of the selector. Exactly how this93* synchronization is performed is implementation-dependent: In a naive94* implementation, reading or writing the interest set may block indefinitely95* if a selection operation is already in progress; in a high-performance96* implementation, reading or writing the interest set may block briefly, if at97* all. In any case, a selection operation will always use the interest-set98* value that was current at the moment that the operation began. </p>99*100*101* @author Mark Reinhold102* @author JSR-51 Expert Group103* @since 1.4104*105* @see SelectableChannel106* @see Selector107*/108109public abstract class SelectionKey {110111/**112* Constructs an instance of this class.113*/114protected SelectionKey() { }115116117// -- Channel and selector operations --118119/**120* Returns the channel for which this key was created. This method will121* continue to return the channel even after the key is cancelled.122*123* @return This key's channel124*/125public abstract SelectableChannel channel();126127/**128* Returns the selector for which this key was created. This method will129* continue to return the selector even after the key is cancelled.130*131* @return This key's selector132*/133public abstract Selector selector();134135/**136* Tells whether or not this key is valid.137*138* <p> A key is valid upon creation and remains so until it is cancelled,139* its channel is closed, or its selector is closed. </p>140*141* @return <tt>true</tt> if, and only if, this key is valid142*/143public abstract boolean isValid();144145/**146* Requests that the registration of this key's channel with its selector147* be cancelled. Upon return the key will be invalid and will have been148* added to its selector's cancelled-key set. The key will be removed from149* all of the selector's key sets during the next selection operation.150*151* <p> If this key has already been cancelled then invoking this method has152* no effect. Once cancelled, a key remains forever invalid. </p>153*154* <p> This method may be invoked at any time. It synchronizes on the155* selector's cancelled-key set, and therefore may block briefly if invoked156* concurrently with a cancellation or selection operation involving the157* same selector. </p>158*/159public abstract void cancel();160161162// -- Operation-set accessors --163164/**165* Retrieves this key's interest set.166*167* <p> It is guaranteed that the returned set will only contain operation168* bits that are valid for this key's channel.169*170* <p> This method may be invoked at any time. Whether or not it blocks,171* and for how long, is implementation-dependent. </p>172*173* @return This key's interest set174*175* @throws CancelledKeyException176* If this key has been cancelled177*/178public abstract int interestOps();179180/**181* Sets this key's interest set to the given value.182*183* <p> This method may be invoked at any time. Whether or not it blocks,184* and for how long, is implementation-dependent. </p>185*186* @param ops The new interest set187*188* @return This selection key189*190* @throws IllegalArgumentException191* If a bit in the set does not correspond to an operation that192* is supported by this key's channel, that is, if193* {@code (ops & ~channel().validOps()) != 0}194*195* @throws CancelledKeyException196* If this key has been cancelled197*/198public abstract SelectionKey interestOps(int ops);199200/**201* Retrieves this key's ready-operation set.202*203* <p> It is guaranteed that the returned set will only contain operation204* bits that are valid for this key's channel. </p>205*206* @return This key's ready-operation set207*208* @throws CancelledKeyException209* If this key has been cancelled210*/211public abstract int readyOps();212213214// -- Operation bits and bit-testing convenience methods --215216/**217* Operation-set bit for read operations.218*219* <p> Suppose that a selection key's interest set contains220* <tt>OP_READ</tt> at the start of a <a221* href="Selector.html#selop">selection operation</a>. If the selector222* detects that the corresponding channel is ready for reading, has reached223* end-of-stream, has been remotely shut down for further reading, or has224* an error pending, then it will add <tt>OP_READ</tt> to the key's225* ready-operation set and add the key to its selected-key set. </p>226*/227public static final int OP_READ = 1 << 0;228229/**230* Operation-set bit for write operations.231*232* <p> Suppose that a selection key's interest set contains233* <tt>OP_WRITE</tt> at the start of a <a234* href="Selector.html#selop">selection operation</a>. If the selector235* detects that the corresponding channel is ready for writing, has been236* remotely shut down for further writing, or has an error pending, then it237* will add <tt>OP_WRITE</tt> to the key's ready set and add the key to its238* selected-key set. </p>239*/240public static final int OP_WRITE = 1 << 2;241242/**243* Operation-set bit for socket-connect operations.244*245* <p> Suppose that a selection key's interest set contains246* <tt>OP_CONNECT</tt> at the start of a <a247* href="Selector.html#selop">selection operation</a>. If the selector248* detects that the corresponding socket channel is ready to complete its249* connection sequence, or has an error pending, then it will add250* <tt>OP_CONNECT</tt> to the key's ready set and add the key to its251* selected-key set. </p>252*/253public static final int OP_CONNECT = 1 << 3;254255/**256* Operation-set bit for socket-accept operations.257*258* <p> Suppose that a selection key's interest set contains259* <tt>OP_ACCEPT</tt> at the start of a <a260* href="Selector.html#selop">selection operation</a>. If the selector261* detects that the corresponding server-socket channel is ready to accept262* another connection, or has an error pending, then it will add263* <tt>OP_ACCEPT</tt> to the key's ready set and add the key to its264* selected-key set. </p>265*/266public static final int OP_ACCEPT = 1 << 4;267268/**269* Tests whether this key's channel is ready for reading.270*271* <p> An invocation of this method of the form <tt>k.isReadable()</tt>272* behaves in exactly the same way as the expression273*274* <blockquote><pre>{@code275* k.readyOps() & OP_READ != 0276* }</pre></blockquote>277*278* <p> If this key's channel does not support read operations then this279* method always returns <tt>false</tt>. </p>280*281* @return <tt>true</tt> if, and only if,282{@code readyOps() & OP_READ} is nonzero283*284* @throws CancelledKeyException285* If this key has been cancelled286*/287public final boolean isReadable() {288return (readyOps() & OP_READ) != 0;289}290291/**292* Tests whether this key's channel is ready for writing.293*294* <p> An invocation of this method of the form <tt>k.isWritable()</tt>295* behaves in exactly the same way as the expression296*297* <blockquote><pre>{@code298* k.readyOps() & OP_WRITE != 0299* }</pre></blockquote>300*301* <p> If this key's channel does not support write operations then this302* method always returns <tt>false</tt>. </p>303*304* @return <tt>true</tt> if, and only if,305* {@code readyOps() & OP_WRITE} is nonzero306*307* @throws CancelledKeyException308* If this key has been cancelled309*/310public final boolean isWritable() {311return (readyOps() & OP_WRITE) != 0;312}313314/**315* Tests whether this key's channel has either finished, or failed to316* finish, its socket-connection operation.317*318* <p> An invocation of this method of the form <tt>k.isConnectable()</tt>319* behaves in exactly the same way as the expression320*321* <blockquote><pre>{@code322* k.readyOps() & OP_CONNECT != 0323* }</pre></blockquote>324*325* <p> If this key's channel does not support socket-connect operations326* then this method always returns <tt>false</tt>. </p>327*328* @return <tt>true</tt> if, and only if,329* {@code readyOps() & OP_CONNECT} is nonzero330*331* @throws CancelledKeyException332* If this key has been cancelled333*/334public final boolean isConnectable() {335return (readyOps() & OP_CONNECT) != 0;336}337338/**339* Tests whether this key's channel is ready to accept a new socket340* connection.341*342* <p> An invocation of this method of the form <tt>k.isAcceptable()</tt>343* behaves in exactly the same way as the expression344*345* <blockquote><pre>{@code346* k.readyOps() & OP_ACCEPT != 0347* }</pre></blockquote>348*349* <p> If this key's channel does not support socket-accept operations then350* this method always returns <tt>false</tt>. </p>351*352* @return <tt>true</tt> if, and only if,353* {@code readyOps() & OP_ACCEPT} is nonzero354*355* @throws CancelledKeyException356* If this key has been cancelled357*/358public final boolean isAcceptable() {359return (readyOps() & OP_ACCEPT) != 0;360}361362363// -- Attachments --364365private volatile Object attachment = null;366367private static final AtomicReferenceFieldUpdater<SelectionKey,Object>368attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(369SelectionKey.class, Object.class, "attachment"370);371372/**373* Attaches the given object to this key.374*375* <p> An attached object may later be retrieved via the {@link #attachment()376* attachment} method. Only one object may be attached at a time; invoking377* this method causes any previous attachment to be discarded. The current378* attachment may be discarded by attaching <tt>null</tt>. </p>379*380* @param ob381* The object to be attached; may be <tt>null</tt>382*383* @return The previously-attached object, if any,384* otherwise <tt>null</tt>385*/386public final Object attach(Object ob) {387return attachmentUpdater.getAndSet(this, ob);388}389390/**391* Retrieves the current attachment.392*393* @return The object currently attached to this key,394* or <tt>null</tt> if there is no attachment395*/396public final Object attachment() {397return attachment;398}399400}401402403