Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/Selector.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.io.Closeable;28import java.io.IOException;29import java.nio.channels.spi.SelectorProvider;30import java.util.Set;313233/**34* A multiplexor of {@link SelectableChannel} objects.35*36* <p> A selector may be created by invoking the {@link #open open} method of37* this class, which will use the system's default {@link38* java.nio.channels.spi.SelectorProvider selector provider} to39* create a new selector. A selector may also be created by invoking the40* {@link java.nio.channels.spi.SelectorProvider#openSelector openSelector}41* method of a custom selector provider. A selector remains open until it is42* closed via its {@link #close close} method.43*44* <a name="ks"></a>45*46* <p> A selectable channel's registration with a selector is represented by a47* {@link SelectionKey} object. A selector maintains three sets of selection48* keys:49*50* <ul>51*52* <li><p> The <i>key set</i> contains the keys representing the current53* channel registrations of this selector. This set is returned by the54* {@link #keys() keys} method. </p></li>55*56* <li><p> The <i>selected-key set</i> is the set of keys such that each57* key's channel was detected to be ready for at least one of the operations58* identified in the key's interest set during a prior selection operation.59* This set is returned by the {@link #selectedKeys() selectedKeys} method.60* The selected-key set is always a subset of the key set. </p></li>61*62* <li><p> The <i>cancelled-key</i> set is the set of keys that have been63* cancelled but whose channels have not yet been deregistered. This set is64* not directly accessible. The cancelled-key set is always a subset of the65* key set. </p></li>66*67* </ul>68*69* <p> All three sets are empty in a newly-created selector.70*71* <p> A key is added to a selector's key set as a side effect of registering a72* channel via the channel's {@link SelectableChannel#register(Selector,int)73* register} method. Cancelled keys are removed from the key set during74* selection operations. The key set itself is not directly modifiable.75*76* <p> A key is added to its selector's cancelled-key set when it is cancelled,77* whether by closing its channel or by invoking its {@link SelectionKey#cancel78* cancel} method. Cancelling a key will cause its channel to be deregistered79* during the next selection operation, at which time the key will removed from80* all of the selector's key sets.81*82* <a name="sks"></a><p> Keys are added to the selected-key set by selection83* operations. A key may be removed directly from the selected-key set by84* invoking the set's {@link java.util.Set#remove(java.lang.Object) remove}85* method or by invoking the {@link java.util.Iterator#remove() remove} method86* of an {@link java.util.Iterator iterator} obtained from the87* set. Keys are never removed from the selected-key set in any other way;88* they are not, in particular, removed as a side effect of selection89* operations. Keys may not be added directly to the selected-key set. </p>90*91*92* <a name="selop"></a>93* <h2>Selection</h2>94*95* <p> During each selection operation, keys may be added to and removed from a96* selector's selected-key set and may be removed from its key and97* cancelled-key sets. Selection is performed by the {@link #select()}, {@link98* #select(long)}, and {@link #selectNow()} methods, and involves three steps:99* </p>100*101* <ol>102*103* <li><p> Each key in the cancelled-key set is removed from each key set of104* which it is a member, and its channel is deregistered. This step leaves105* the cancelled-key set empty. </p></li>106*107* <li><p> The underlying operating system is queried for an update as to the108* readiness of each remaining channel to perform any of the operations109* identified by its key's interest set as of the moment that the selection110* operation began. For a channel that is ready for at least one such111* operation, one of the following two actions is performed: </p>112*113* <ol>114*115* <li><p> If the channel's key is not already in the selected-key set then116* it is added to that set and its ready-operation set is modified to117* identify exactly those operations for which the channel is now reported118* to be ready. Any readiness information previously recorded in the ready119* set is discarded. </p></li>120*121* <li><p> Otherwise the channel's key is already in the selected-key set,122* so its ready-operation set is modified to identify any new operations123* for which the channel is reported to be ready. Any readiness124* information previously recorded in the ready set is preserved; in other125* words, the ready set returned by the underlying system is126* bitwise-disjoined into the key's current ready set. </p></li>127*128* </ol>129*130* If all of the keys in the key set at the start of this step have empty131* interest sets then neither the selected-key set nor any of the keys'132* ready-operation sets will be updated.133*134* <li><p> If any keys were added to the cancelled-key set while step (2) was135* in progress then they are processed as in step (1). </p></li>136*137* </ol>138*139* <p> Whether or not a selection operation blocks to wait for one or more140* channels to become ready, and if so for how long, is the only essential141* difference between the three selection methods. </p>142*143*144* <h2>Concurrency</h2>145*146* <p> Selectors are themselves safe for use by multiple concurrent threads;147* their key sets, however, are not.148*149* <p> The selection operations synchronize on the selector itself, on the key150* set, and on the selected-key set, in that order. They also synchronize on151* the cancelled-key set during steps (1) and (3) above.152*153* <p> Changes made to the interest sets of a selector's keys while a154* selection operation is in progress have no effect upon that operation; they155* will be seen by the next selection operation.156*157* <p> Keys may be cancelled and channels may be closed at any time. Hence the158* presence of a key in one or more of a selector's key sets does not imply159* that the key is valid or that its channel is open. Application code should160* be careful to synchronize and check these conditions as necessary if there161* is any possibility that another thread will cancel a key or close a channel.162*163* <p> A thread blocked in one of the {@link #select()} or {@link164* #select(long)} methods may be interrupted by some other thread in one of165* three ways:166*167* <ul>168*169* <li><p> By invoking the selector's {@link #wakeup wakeup} method,170* </p></li>171*172* <li><p> By invoking the selector's {@link #close close} method, or173* </p></li>174*175* <li><p> By invoking the blocked thread's {@link176* java.lang.Thread#interrupt() interrupt} method, in which case its177* interrupt status will be set and the selector's {@link #wakeup wakeup}178* method will be invoked. </p></li>179*180* </ul>181*182* <p> The {@link #close close} method synchronizes on the selector and all183* three key sets in the same order as in a selection operation.184*185* <a name="ksc"></a>186*187* <p> A selector's key and selected-key sets are not, in general, safe for use188* by multiple concurrent threads. If such a thread might modify one of these189* sets directly then access should be controlled by synchronizing on the set190* itself. The iterators returned by these sets' {@link191* java.util.Set#iterator() iterator} methods are <i>fail-fast:</i> If the set192* is modified after the iterator is created, in any way except by invoking the193* iterator's own {@link java.util.Iterator#remove() remove} method, then a194* {@link java.util.ConcurrentModificationException} will be thrown. </p>195*196*197* @author Mark Reinhold198* @author JSR-51 Expert Group199* @since 1.4200*201* @see SelectableChannel202* @see SelectionKey203*/204205public abstract class Selector implements Closeable {206207/**208* Initializes a new instance of this class.209*/210protected Selector() { }211212/**213* Opens a selector.214*215* <p> The new selector is created by invoking the {@link216* java.nio.channels.spi.SelectorProvider#openSelector openSelector} method217* of the system-wide default {@link218* java.nio.channels.spi.SelectorProvider} object. </p>219*220* @return A new selector221*222* @throws IOException223* If an I/O error occurs224*/225public static Selector open() throws IOException {226return SelectorProvider.provider().openSelector();227}228229/**230* Tells whether or not this selector is open.231*232* @return <tt>true</tt> if, and only if, this selector is open233*/234public abstract boolean isOpen();235236/**237* Returns the provider that created this channel.238*239* @return The provider that created this channel240*/241public abstract SelectorProvider provider();242243/**244* Returns this selector's key set.245*246* <p> The key set is not directly modifiable. A key is removed only after247* it has been cancelled and its channel has been deregistered. Any248* attempt to modify the key set will cause an {@link249* UnsupportedOperationException} to be thrown.250*251* <p> The key set is <a href="#ksc">not thread-safe</a>. </p>252*253* @return This selector's key set254*255* @throws ClosedSelectorException256* If this selector is closed257*/258public abstract Set<SelectionKey> keys();259260/**261* Returns this selector's selected-key set.262*263* <p> Keys may be removed from, but not directly added to, the264* selected-key set. Any attempt to add an object to the key set will265* cause an {@link UnsupportedOperationException} to be thrown.266*267* <p> The selected-key set is <a href="#ksc">not thread-safe</a>. </p>268*269* @return This selector's selected-key set270*271* @throws ClosedSelectorException272* If this selector is closed273*/274public abstract Set<SelectionKey> selectedKeys();275276/**277* Selects a set of keys whose corresponding channels are ready for I/O278* operations.279*280* <p> This method performs a non-blocking <a href="#selop">selection281* operation</a>. If no channels have become selectable since the previous282* selection operation then this method immediately returns zero.283*284* <p> Invoking this method clears the effect of any previous invocations285* of the {@link #wakeup wakeup} method. </p>286*287* @return The number of keys, possibly zero, whose ready-operation sets288* were updated by the selection operation289*290* @throws IOException291* If an I/O error occurs292*293* @throws ClosedSelectorException294* If this selector is closed295*/296public abstract int selectNow() throws IOException;297298/**299* Selects a set of keys whose corresponding channels are ready for I/O300* operations.301*302* <p> This method performs a blocking <a href="#selop">selection303* operation</a>. It returns only after at least one channel is selected,304* this selector's {@link #wakeup wakeup} method is invoked, the current305* thread is interrupted, or the given timeout period expires, whichever306* comes first.307*308* <p> This method does not offer real-time guarantees: It schedules the309* timeout as if by invoking the {@link Object#wait(long)} method. </p>310*311* @param timeout If positive, block for up to <tt>timeout</tt>312* milliseconds, more or less, while waiting for a313* channel to become ready; if zero, block indefinitely;314* must not be negative315*316* @return The number of keys, possibly zero,317* whose ready-operation sets were updated318*319* @throws IOException320* If an I/O error occurs321*322* @throws ClosedSelectorException323* If this selector is closed324*325* @throws IllegalArgumentException326* If the value of the timeout argument is negative327*/328public abstract int select(long timeout)329throws IOException;330331/**332* Selects a set of keys whose corresponding channels are ready for I/O333* operations.334*335* <p> This method performs a blocking <a href="#selop">selection336* operation</a>. It returns only after at least one channel is selected,337* this selector's {@link #wakeup wakeup} method is invoked, or the current338* thread is interrupted, whichever comes first. </p>339*340* @return The number of keys, possibly zero,341* whose ready-operation sets were updated342*343* @throws IOException344* If an I/O error occurs345*346* @throws ClosedSelectorException347* If this selector is closed348*/349public abstract int select() throws IOException;350351/**352* Causes the first selection operation that has not yet returned to return353* immediately.354*355* <p> If another thread is currently blocked in an invocation of the356* {@link #select()} or {@link #select(long)} methods then that invocation357* will return immediately. If no selection operation is currently in358* progress then the next invocation of one of these methods will return359* immediately unless the {@link #selectNow()} method is invoked in the360* meantime. In any case the value returned by that invocation may be361* non-zero. Subsequent invocations of the {@link #select()} or {@link362* #select(long)} methods will block as usual unless this method is invoked363* again in the meantime.364*365* <p> Invoking this method more than once between two successive selection366* operations has the same effect as invoking it just once. </p>367*368* @return This selector369*/370public abstract Selector wakeup();371372/**373* Closes this selector.374*375* <p> If a thread is currently blocked in one of this selector's selection376* methods then it is interrupted as if by invoking the selector's {@link377* #wakeup wakeup} method.378*379* <p> Any uncancelled keys still associated with this selector are380* invalidated, their channels are deregistered, and any other resources381* associated with this selector are released.382*383* <p> If this selector is already closed then invoking this method has no384* effect.385*386* <p> After a selector is closed, any further attempt to use it, except by387* invoking this method or the {@link #wakeup wakeup} method, will cause a388* {@link ClosedSelectorException} to be thrown. </p>389*390* @throws IOException391* If an I/O error occurs392*/393public abstract void close() throws IOException;394395}396397398