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.io.Closeable; 29 import java.io.IOException; 30 import java.nio.channels.spi.SelectorProvider; 31 import java.util.Objects; 32 import java.util.Set; 33 import java.util.function.Consumer; 34 35 36 /** 37 * A multiplexor of {@link SelectableChannel} objects. 38 * 39 * <p> A selector may be created by invoking the {@link #open open} method of 40 * this class, which will use the system's default {@link 41 * java.nio.channels.spi.SelectorProvider selector provider} to 42 * create a new selector. A selector may also be created by invoking the 43 * {@link java.nio.channels.spi.SelectorProvider#openSelector openSelector} 44 * method of a custom selector provider. A selector remains open until it is 45 * closed via its {@link #close close} method. 46 * 47 * <a id="ks"></a> 48 * 49 * <p> A selectable channel's registration with a selector is represented by a 50 * {@link SelectionKey} object. A selector maintains three sets of selection 51 * keys: 52 * 53 * <ul> 54 * 55 * <li><p> The <i>key set</i> contains the keys representing the current 56 * channel registrations of this selector. This set is returned by the 57 * {@link #keys() keys} method. </p></li> 58 * 59 * <li><p> The <i>selected-key set</i> is the set of keys such that each 60 * key's channel was detected to be ready for at least one of the operations 61 * identified in the key's interest set during a prior selection operation 62 * that adds keys or updates keys in the set. 63 * This set is returned by the {@link #selectedKeys() selectedKeys} method. 64 * The selected-key set is always a subset of the key set. </p></li> 65 * 66 * <li><p> The <i>cancelled-key</i> set is the set of keys that have been 67 * cancelled but whose channels have not yet been deregistered. This set is 68 * not directly accessible. The cancelled-key set is always a subset of the 69 * key set. </p></li> 70 * 71 * </ul> 72 * 73 * <p> All three sets are empty in a newly-created selector. 74 * 75 * <p> A key is added to a selector's key set as a side effect of registering a 76 * channel via the channel's {@link SelectableChannel#register(Selector,int) 77 * register} method. Cancelled keys are removed from the key set during 78 * selection operations. The key set itself is not directly modifiable. 79 * 80 * <p> A key is added to its selector's cancelled-key set when it is cancelled, 81 * whether by closing its channel or by invoking its {@link SelectionKey#cancel 82 * cancel} method. Cancelling a key will cause its channel to be deregistered 83 * during the next selection operation, at which time the key will be removed 84 * from all of the selector's key sets. 85 * 86 * <a id="sks"></a><p> Keys are added to the selected-key set by selection 87 * operations. A key may be removed directly from the selected-key set by 88 * invoking the set's {@link java.util.Set#remove(java.lang.Object) remove} 89 * method or by invoking the {@link java.util.Iterator#remove() remove} method 90 * of an {@link java.util.Iterator iterator} obtained from the set. 91 * All keys may be removed from the selected-key set by invoking the set's 92 * {@link java.util.Set#clear() clear} method. Keys may not be added directly 93 * to the selected-key set. </p> 94 * 95 * <a id="selop"></a> 96 * <h2>Selection</h2> 97 * 98 * <p> A selection operation queries the underlying operating system for an 99 * update as to the readiness of each registered channel to perform any of the 100 * operations identified by its key's interest set. There are two forms of 101 * selection operation: 102 * 103 * <ol> 104 * 105 * <li><p> The {@link #select()}, {@link #select(long)}, and {@link #selectNow()} 106 * methods add the keys of channels ready to perform an operation to the 107 * selected-key set, or update the ready-operation set of keys already in the 108 * selected-key set. </p></li> 109 * 110 * <li><p> The {@link #select(Consumer)}, {@link #select(Consumer, long)}, and 111 * {@link #selectNow(Consumer)} methods perform an <i>action</i> on the key 112 * of each channel that is ready to perform an operation. These methods do 113 * not add to the selected-key set. </p></li> 114 * 115 * </ol> 116 * 117 * <h3>Selection operations that add to the selected-key set</h3> 118 * 119 * <p> During each selection operation, keys may be added to and removed from a 120 * selector's selected-key set and may be removed from its key and 121 * cancelled-key sets. Selection is performed by the {@link #select()}, {@link 122 * #select(long)}, and {@link #selectNow()} methods, and involves three steps: 123 * </p> 124 * 125 * <ol> 126 * 127 * <li><p> Each key in the cancelled-key set is removed from each key set of 128 * which it is a member, and its channel is deregistered. This step leaves 129 * the cancelled-key set empty. </p></li> 130 * 131 * <li><p> The underlying operating system is queried for an update as to the 132 * readiness of each remaining channel to perform any of the operations 133 * identified by its key's interest set as of the moment that the selection 134 * operation began. For a channel that is ready for at least one such 135 * operation, one of the following two actions is performed: </p> 136 * 137 * <ol> 138 * 139 * <li><p> If the channel's key is not already in the selected-key set then 140 * it is added to that set and its ready-operation set is modified to 141 * identify exactly those operations for which the channel is now reported 142 * to be ready. Any readiness information previously recorded in the ready 143 * set is discarded. </p></li> 144 * 145 * <li><p> Otherwise the channel's key is already in the selected-key set, 146 * so its ready-operation set is modified to identify any new operations 147 * for which the channel is reported to be ready. Any readiness 148 * information previously recorded in the ready set is preserved; in other 149 * words, the ready set returned by the underlying system is 150 * bitwise-disjoined into the key's current ready set. </p></li> 151 * 152 * </ol> 153 * 154 * If all of the keys in the key set at the start of this step have empty 155 * interest sets then neither the selected-key set nor any of the keys' 156 * ready-operation sets will be updated. 157 * 158 * <li><p> If any keys were added to the cancelled-key set while step (2) was 159 * in progress then they are processed as in step (1). </p></li> 160 * 161 * </ol> 162 * 163 * <p> Whether or not a selection operation blocks to wait for one or more 164 * channels to become ready, and if so for how long, is the only essential 165 * difference between the three selection methods. </p> 166 * 167 * 168 * <h3>Selection operations that perform an action on selected keys</h3> 169 * 170 * <p> During each selection operation, keys may be removed from the selector's 171 * key, selected-key, and cancelled-key sets. Selection is performed by the 172 * {@link #select(Consumer)}, {@link #select(Consumer,long)}, and {@link 173 * #selectNow(Consumer)} methods, and involves three steps: </p> 174 * 175 * <ol> 176 * 177 * <li><p> Each key in the cancelled-key set is removed from each key set of 178 * which it is a member, and its channel is deregistered. This step leaves 179 * the cancelled-key set empty. </p></li> 180 * 181 * <li><p> The underlying operating system is queried for an update as to the 182 * readiness of each remaining channel to perform any of the operations 183 * identified by its key's interest set as of the moment that the selection 184 * operation began. 185 * 186 * <p> For a channel that is ready for at least one such operation, the 187 * ready-operation set of the channel's key is set to identify exactly the 188 * operations for which the channel is ready and the <i>action</i> specified 189 * to the {@code select} method is invoked to consume the channel's key. Any 190 * readiness information previously recorded in the ready set is discarded 191 * prior to invoking the <i>action</i>. 192 * 193 * <p> Alternatively, where a channel is ready for more than one operation, 194 * the <i>action</i> may be invoked more than once with the channel's key and 195 * ready-operation set modified to a subset of the operations for which the 196 * channel is ready. Where the <i>action</i> is invoked more than once for 197 * the same key then its ready-operation set never contains operation bits 198 * that were contained in the set at previous calls to the <i>action</i> 199 * in the same selection operation. </p></li> 200 * 201 * <li><p> If any keys were added to the cancelled-key set while step (2) was 202 * in progress then they are processed as in step (1). </p></li> 203 * 204 * </ol> 205 * 206 * 207 * <h2>Concurrency</h2> 208 * 209 * <p> A Selector and its key set are safe for use by multiple concurrent 210 * threads. Its selected-key set and cancelled-key set, however, are not. 211 * 212 * <p> The selection operations synchronize on the selector itself, on the 213 * selected-key set, in that order. They also synchronize on the cancelled-key 214 * set during steps (1) and (3) above. 215 * 216 * <p> Changes made to the interest sets of a selector's keys while a 217 * selection operation is in progress have no effect upon that operation; they 218 * will be seen by the next selection operation. 219 * 220 * <p> Keys may be cancelled and channels may be closed at any time. Hence the 221 * presence of a key in one or more of a selector's key sets does not imply 222 * that the key is valid or that its channel is open. Application code should 223 * be careful to synchronize and check these conditions as necessary if there 224 * is any possibility that another thread will cancel a key or close a channel. 225 * 226 * <p> A thread blocked in a selection operation may be interrupted by some 227 * other thread in one of three ways: 228 * 229 * <ul> 230 * 231 * <li><p> By invoking the selector's {@link #wakeup wakeup} method, 232 * </p></li> 233 * 234 * <li><p> By invoking the selector's {@link #close close} method, or 235 * </p></li> 236 * 237 * <li><p> By invoking the blocked thread's {@link 238 * java.lang.Thread#interrupt() interrupt} method, in which case its 239 * interrupt status will be set and the selector's {@link #wakeup wakeup} 240 * method will be invoked. </p></li> 241 * 242 * </ul> 243 * 244 * <p> The {@link #close close} method synchronizes on the selector and its 245 * selected-key set in the same order as in a selection operation. 246 * 247 * <a id="ksc"></a> 248 * <p> A Selector's key set is safe for use by multiple concurrent threads. 249 * Retrieval operations from the key set do not generally block and so may 250 * overlap with new registrations that add to the set, or with the cancellation 251 * steps of selection operations that remove keys from the set. Iterators and 252 * spliterators return elements reflecting the state of the set at some point at 253 * or since the creation of the iterator/spliterator. They do not throw 254 * {@link java.util.ConcurrentModificationException ConcurrentModificationException}. 255 * 256 * <a id="sksc"></a> 257 * <p> A selector's selected-key set is not, in general, safe for use by 258 * multiple concurrent threads. If such a thread might modify the set directly 259 * then access should be controlled by synchronizing on the set itself. The 260 * iterators returned by the set's {@link java.util.Set#iterator() iterator} 261 * methods are <i>fail-fast:</i> If the set is modified after the iterator is 262 * created, in any way except by invoking the iterator's own {@link 263 * java.util.Iterator#remove() remove} method, then a {@link 264 * java.util.ConcurrentModificationException} will be thrown. </p> 265 * 266 * @author Mark Reinhold 267 * @author JSR-51 Expert Group 268 * @since 1.4 269 * 270 * @see SelectableChannel 271 * @see SelectionKey 272 */ 273 274 public abstract class Selector implements Closeable { 275 276 /** 277 * Initializes a new instance of this class. 278 */ Selector()279 protected Selector() { } 280 281 /** 282 * Opens a selector. 283 * 284 * <p> The new selector is created by invoking the {@link 285 * java.nio.channels.spi.SelectorProvider#openSelector openSelector} method 286 * of the system-wide default {@link 287 * java.nio.channels.spi.SelectorProvider} object. </p> 288 * 289 * @return A new selector 290 * 291 * @throws IOException 292 * If an I/O error occurs 293 */ open()294 public static Selector open() throws IOException { 295 return SelectorProvider.provider().openSelector(); 296 } 297 298 /** 299 * Tells whether or not this selector is open. 300 * 301 * @return {@code true} if, and only if, this selector is open 302 */ isOpen()303 public abstract boolean isOpen(); 304 305 /** 306 * Returns the provider that created this channel. 307 * 308 * @return The provider that created this channel 309 */ provider()310 public abstract SelectorProvider provider(); 311 312 /** 313 * Returns this selector's key set. 314 * 315 * <p> The key set is not directly modifiable. A key is removed only after 316 * it has been cancelled and its channel has been deregistered. Any 317 * attempt to modify the key set will cause an {@link 318 * UnsupportedOperationException} to be thrown. 319 * 320 * <p> The set is <a href="#ksc">safe</a> for use by multiple concurrent 321 * threads. </p> 322 * 323 * @return This selector's key set 324 * 325 * @throws ClosedSelectorException 326 * If this selector is closed 327 */ keys()328 public abstract Set<SelectionKey> keys(); 329 330 /** 331 * Returns this selector's selected-key set. 332 * 333 * <p> Keys may be removed from, but not directly added to, the 334 * selected-key set. Any attempt to add an object to the key set will 335 * cause an {@link UnsupportedOperationException} to be thrown. 336 * 337 * <p> The selected-key set is <a href="#sksc">not thread-safe</a>. </p> 338 * 339 * @return This selector's selected-key set 340 * 341 * @throws ClosedSelectorException 342 * If this selector is closed 343 */ selectedKeys()344 public abstract Set<SelectionKey> selectedKeys(); 345 346 /** 347 * Selects a set of keys whose corresponding channels are ready for I/O 348 * operations. 349 * 350 * <p> This method performs a non-blocking <a href="#selop">selection 351 * operation</a>. If no channels have become selectable since the previous 352 * selection operation then this method immediately returns zero. 353 * 354 * <p> Invoking this method clears the effect of any previous invocations 355 * of the {@link #wakeup wakeup} method. </p> 356 * 357 * @return The number of keys, possibly zero, whose ready-operation sets 358 * were updated by the selection operation 359 * 360 * @throws IOException 361 * If an I/O error occurs 362 * 363 * @throws ClosedSelectorException 364 * If this selector is closed 365 */ selectNow()366 public abstract int selectNow() throws IOException; 367 368 /** 369 * Selects a set of keys whose corresponding channels are ready for I/O 370 * operations. 371 * 372 * <p> This method performs a blocking <a href="#selop">selection 373 * operation</a>. It returns only after at least one channel is selected, 374 * this selector's {@link #wakeup wakeup} method is invoked, the current 375 * thread is interrupted, or the given timeout period expires, whichever 376 * comes first. 377 * 378 * <p> This method does not offer real-time guarantees: It schedules the 379 * timeout as if by invoking the {@link Object#wait(long)} method. </p> 380 * 381 * @param timeout If positive, block for up to {@code timeout} 382 * milliseconds, more or less, while waiting for a 383 * channel to become ready; if zero, block indefinitely; 384 * must not be negative 385 * 386 * @return The number of keys, possibly zero, 387 * whose ready-operation sets were updated 388 * 389 * @throws IOException 390 * If an I/O error occurs 391 * 392 * @throws ClosedSelectorException 393 * If this selector is closed 394 * 395 * @throws IllegalArgumentException 396 * If the value of the timeout argument is negative 397 */ select(long timeout)398 public abstract int select(long timeout) throws IOException; 399 400 /** 401 * Selects a set of keys whose corresponding channels are ready for I/O 402 * operations. 403 * 404 * <p> This method performs a blocking <a href="#selop">selection 405 * operation</a>. It returns only after at least one channel is selected, 406 * this selector's {@link #wakeup wakeup} method is invoked, or the current 407 * thread is interrupted, whichever comes first. </p> 408 * 409 * @return The number of keys, possibly zero, 410 * whose ready-operation sets were updated 411 * 412 * @throws IOException 413 * If an I/O error occurs 414 * 415 * @throws ClosedSelectorException 416 * If this selector is closed 417 */ select()418 public abstract int select() throws IOException; 419 420 /** 421 * Selects and performs an action on the keys whose corresponding channels 422 * are ready for I/O operations. 423 * 424 * <p> This method performs a blocking <a href="#selop">selection 425 * operation</a>. It wakes up from querying the operating system only when 426 * at least one channel is selected, this selector's {@link #wakeup wakeup} 427 * method is invoked, the current thread is interrupted, or the given 428 * timeout period expires, whichever comes first. 429 * 430 * <p> The specified <i>action</i>'s {@link Consumer#accept(Object) accept} 431 * method is invoked with the key for each channel that is ready to perform 432 * an operation identified by its key's interest set. The {@code accept} 433 * method may be invoked more than once for the same key but with the 434 * ready-operation set containing a subset of the operations for which the 435 * channel is ready (as described above). The {@code accept} method is 436 * invoked while synchronized on the selector and its selected-key set. 437 * Great care must be taken to avoid deadlocking with other threads that 438 * also synchronize on these objects. Selection operations are not reentrant 439 * in general and consequently the <i>action</i> should take great care not 440 * to attempt a selection operation on the same selector. The behavior when 441 * attempting a reentrant selection operation is implementation specific and 442 * therefore not specified. If the <i>action</i> closes the selector then 443 * {@code ClosedSelectorException} is thrown when the action completes. 444 * The <i>action</i> is not prohibited from closing channels registered with 445 * the selector, nor prohibited from cancelling keys or changing a key's 446 * interest set. If a channel is selected but its key is cancelled or its 447 * interest set changed before the <i>action</i> is performed on the key 448 * then it is implementation specific as to whether the <i>action</i> is 449 * invoked (it may be invoked with an {@link SelectionKey#isValid() invalid} 450 * key). Exceptions thrown by the action are relayed to the caller. 451 * 452 * <p> This method does not offer real-time guarantees: It schedules the 453 * timeout as if by invoking the {@link Object#wait(long)} method. 454 * 455 * @implSpec The default implementation removes all keys from the 456 * selected-key set, invokes {@link #select(long) select(long)} with the 457 * given timeout and then performs the action for each key added to the 458 * selected-key set. The default implementation does not detect the action 459 * performing a reentrant selection operation. The selected-key set may 460 * or may not be empty on completion of the default implementation. 461 * 462 * @param action The action to perform 463 * 464 * @param timeout If positive, block for up to {@code timeout} 465 * milliseconds, more or less, while waiting for a 466 * channel to become ready; if zero, block indefinitely; 467 * must not be negative 468 * 469 * @return The number of unique keys consumed, possibly zero 470 * 471 * @throws IOException 472 * If an I/O error occurs 473 * 474 * @throws ClosedSelectorException 475 * If this selector is closed or is closed by the action 476 * 477 * @throws IllegalArgumentException 478 * If the value of the timeout argument is negative 479 * 480 * @since 11 481 */ select(Consumer<SelectionKey> action, long timeout)482 public int select(Consumer<SelectionKey> action, long timeout) 483 throws IOException 484 { 485 if (timeout < 0) 486 throw new IllegalArgumentException("Negative timeout"); 487 return doSelect(Objects.requireNonNull(action), timeout); 488 } 489 490 /** 491 * Selects and performs an action on the keys whose corresponding channels 492 * are ready for I/O operations. 493 * 494 * <p> This method performs a blocking <a href="#selop">selection 495 * operation</a>. It wakes up from querying the operating system only when 496 * at least one channel is selected, this selector's {@link #wakeup wakeup} 497 * method is invoked, or the current thread is interrupted, whichever comes 498 * first. 499 * 500 * <p> This method is equivalent to invoking the 2-arg 501 * {@link #select(Consumer, long) select} method with a timeout of {@code 0} 502 * to block indefinitely. </p> 503 * 504 * @implSpec The default implementation invokes the 2-arg {@code select} 505 * method with a timeout of {@code 0}. 506 * 507 * @param action The action to perform 508 * 509 * @return The number of unique keys consumed, possibly zero 510 * 511 * @throws IOException 512 * If an I/O error occurs 513 * 514 * @throws ClosedSelectorException 515 * If this selector is closed or is closed by the action 516 * 517 * @since 11 518 */ select(Consumer<SelectionKey> action)519 public int select(Consumer<SelectionKey> action) throws IOException { 520 return select(action, 0); 521 } 522 523 /** 524 * Selects and performs an action on the keys whose corresponding channels 525 * are ready for I/O operations. 526 * 527 * <p> This method performs a non-blocking <a href="#selop">selection 528 * operation</a>. 529 * 530 * <p> Invoking this method clears the effect of any previous invocations 531 * of the {@link #wakeup wakeup} method. </p> 532 * 533 * @implSpec The default implementation removes all keys from the 534 * selected-key set, invokes {@link #selectNow() selectNow()} and then 535 * performs the action for each key added to the selected-key set. The 536 * default implementation does not detect the action performing a reentrant 537 * selection operation. The selected-key set may or may not be empty on 538 * completion of the default implementation. 539 * 540 * @param action The action to perform 541 * 542 * @return The number of unique keys consumed, possibly zero 543 * 544 * @throws IOException 545 * If an I/O error occurs 546 * 547 * @throws ClosedSelectorException 548 * If this selector is closed or is closed by the action 549 * 550 * @since 11 551 */ selectNow(Consumer<SelectionKey> action)552 public int selectNow(Consumer<SelectionKey> action) throws IOException { 553 return doSelect(Objects.requireNonNull(action), -1); 554 } 555 556 /** 557 * Default implementation of select(Consumer) and selectNow(Consumer). 558 */ doSelect(Consumer<SelectionKey> action, long timeout)559 private int doSelect(Consumer<SelectionKey> action, long timeout) 560 throws IOException 561 { 562 synchronized (this) { 563 Set<SelectionKey> selectedKeys = selectedKeys(); 564 synchronized (selectedKeys) { 565 selectedKeys.clear(); 566 int numKeySelected; 567 if (timeout < 0) { 568 numKeySelected = selectNow(); 569 } else { 570 numKeySelected = select(timeout); 571 } 572 573 // copy selected-key set as action may remove keys 574 Set<SelectionKey> keysToConsume = Set.copyOf(selectedKeys); 575 assert keysToConsume.size() == numKeySelected; 576 selectedKeys.clear(); 577 578 // invoke action for each selected key 579 keysToConsume.forEach(k -> { 580 action.accept(k); 581 if (!isOpen()) 582 throw new ClosedSelectorException(); 583 }); 584 585 return numKeySelected; 586 } 587 } 588 } 589 590 591 /** 592 * Causes the first selection operation that has not yet returned to return 593 * immediately. 594 * 595 * <p> If another thread is currently blocked in a selection operation then 596 * that invocation will return immediately. If no selection operation is 597 * currently in progress then the next invocation of a selection operation 598 * will return immediately unless {@link #selectNow()} or {@link 599 * #selectNow(Consumer)} is invoked in the meantime. In any case the value 600 * returned by that invocation may be non-zero. Subsequent selection 601 * operations will block as usual unless this method is invoked again in the 602 * meantime. 603 * 604 * <p> Invoking this method more than once between two successive selection 605 * operations has the same effect as invoking it just once. </p> 606 * 607 * @return This selector 608 */ wakeup()609 public abstract Selector wakeup(); 610 611 /** 612 * Closes this selector. 613 * 614 * <p> If a thread is currently blocked in one of this selector's selection 615 * methods then it is interrupted as if by invoking the selector's {@link 616 * #wakeup wakeup} method. 617 * 618 * <p> Any uncancelled keys still associated with this selector are 619 * invalidated, their channels are deregistered, and any other resources 620 * associated with this selector are released. 621 * 622 * <p> If this selector is already closed then invoking this method has no 623 * effect. 624 * 625 * <p> After a selector is closed, any further attempt to use it, except by 626 * invoking this method or the {@link #wakeup wakeup} method, will cause a 627 * {@link ClosedSelectorException} to be thrown. </p> 628 * 629 * @throws IOException 630 * If an I/O error occurs 631 */ close()632 public abstract void close() throws IOException; 633 } 634