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 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 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 set. </p> 253 * 254 * <p> 255 * Note an application should not use Selector's select() method to check 256 * <tt>OP_CONNECT</tt> again, once a channel is already connected. Please 257 * see {@link java.nio.channels.Selector#select() Selector.select()} for 258 * more detail. 259 * </p> 260 * 261 */ 262 public static final int OP_CONNECT = 1 << 3; 263 264 /** 265 * Operation-set bit for socket-accept operations. </p> 266 * 267 * <p> Suppose that a selection key's interest set contains 268 * <tt>OP_ACCEPT</tt> at the start of a <a 269 * href="Selector.html#selop">selection operation</a>. If the selector 270 * detects that the corresponding server-socket channel is ready to accept 271 * another connection, or has an error pending, then it will add 272 * <tt>OP_ACCEPT</tt> to the key's ready set and add the key to its 273 * selected-key set. </p> 274 */ 275 public static final int OP_ACCEPT = 1 << 4; 276 277 /** 278 * Tests whether this key's channel is ready for reading. 279 * 280 * <p> An invocation of this method of the form <tt>k.isReadable()</tt> 281 * behaves in exactly the same way as the expression 282 * 283 * <blockquote><pre> 284 * k.readyOps() & OP_READ != 0</pre></blockquote> 285 * 286 * <p> If this key's channel does not support read operations then this 287 * method always returns <tt>false</tt>. </p> 288 * 289 * @return <tt>true</tt> if, and only if, 290 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_READ</tt> is 291 * nonzero 292 * 293 * @throws CancelledKeyException 294 * If this key has been cancelled 295 */ 296 public final boolean isReadable() { 297 return (readyOps() & OP_READ) != 0; 298 } 299 300 /** 301 * Tests whether this key's channel is ready for writing. 302 * 303 * <p> An invocation of this method of the form <tt>k.isWritable()</tt> 304 * behaves in exactly the same way as the expression 305 * 306 * <blockquote><pre> 307 * k.readyOps() & OP_WRITE != 0</pre></blockquote> 308 * 309 * <p> If this key's channel does not support write operations then this 310 * method always returns <tt>false</tt>. </p> 311 * 312 * @return <tt>true</tt> if, and only if, 313 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_WRITE</tt> 314 * is nonzero 315 * 316 * @throws CancelledKeyException 317 * If this key has been cancelled 318 */ 319 public final boolean isWritable() { 320 return (readyOps() & OP_WRITE) != 0; 321 } 322 323 /** 324 * Tests whether this key's channel has either finished, or failed to 325 * finish, its socket-connection operation. 326 * 327 * <p> An invocation of this method of the form <tt>k.isConnectable()</tt> 328 * behaves in exactly the same way as the expression 329 * 330 * <blockquote><pre> 331 * k.readyOps() & OP_CONNECT != 0</pre></blockquote> 332 * 333 * <p> If this key's channel does not support socket-connect operations 334 * then this method always returns <tt>false</tt>. </p> 335 * 336 * @return <tt>true</tt> if, and only if, 337 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_CONNECT</tt> 338 * is nonzero 339 * 340 * @throws CancelledKeyException 341 * If this key has been cancelled 342 */ 343 public final boolean isConnectable() { 344 return (readyOps() & OP_CONNECT) != 0; 345 } 346 347 /** 348 * Tests whether this key's channel is ready to accept a new socket 349 * connection. 350 * 351 * <p> An invocation of this method of the form <tt>k.isAcceptable()</tt> 352 * behaves in exactly the same way as the expression 353 * 354 * <blockquote><pre> 355 * k.readyOps() & OP_ACCEPT != 0</pre></blockquote> 356 * 357 * <p> If this key's channel does not support socket-accept operations then 358 * this method always returns <tt>false</tt>. </p> 359 * 360 * @return <tt>true</tt> if, and only if, 361 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_ACCEPT</tt> 362 * is nonzero 363 * 364 * @throws CancelledKeyException 365 * If this key has been cancelled 366 */ 367 public final boolean isAcceptable() { 368 return (readyOps() & OP_ACCEPT) != 0; 369 } 370 371 372 // -- Attachments -- 373 374 private volatile Object attachment = null; 375 376 private static final AtomicReferenceFieldUpdater<SelectionKey,Object> 377 attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater( 378 SelectionKey.class, Object.class, "attachment" 379 ); 380 381 /** 382 * Attaches the given object to this key. 383 * 384 * <p> An attached object may later be retrieved via the {@link #attachment() 385 * attachment} method. Only one object may be attached at a time; invoking 386 * this method causes any previous attachment to be discarded. The current 387 * attachment may be discarded by attaching <tt>null</tt>. </p> 388 * 389 * @param ob 390 * The object to be attached; may be <tt>null</tt> 391 * 392 * @return The previously-attached object, if any, 393 * otherwise <tt>null</tt> 394 */ 395 public final Object attach(Object ob) { 396 return attachmentUpdater.getAndSet(this, ob); 397 } 398 399 /** 400 * Retrieves the current attachment. </p> 401 * 402 * @return The object currently attached to this key, 403 * or <tt>null</tt> if there is no attachment 404 */ 405 public final Object attachment() { 406 return attachment; 407 } 408 409 }