Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java
38918 views
/*1* Copyright (c) 2007, 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.nio.channels.spi.AsynchronousChannelProvider;28import java.io.IOException;29import java.util.concurrent.ExecutorService;30import java.util.concurrent.ThreadFactory;31import java.util.concurrent.TimeUnit;3233/**34* A grouping of asynchronous channels for the purpose of resource sharing.35*36* <p> An asynchronous channel group encapsulates the mechanics required to37* handle the completion of I/O operations initiated by {@link AsynchronousChannel38* asynchronous channels} that are bound to the group. A group has an associated39* thread pool to which tasks are submitted to handle I/O events and dispatch to40* {@link CompletionHandler completion-handlers} that consume the result of41* asynchronous operations performed on channels in the group. In addition to42* handling I/O events, the pooled threads may also execute other tasks required43* to support the execution of asynchronous I/O operations.44*45* <p> An asynchronous channel group is created by invoking the {@link46* #withFixedThreadPool withFixedThreadPool} or {@link #withCachedThreadPool47* withCachedThreadPool} methods defined here. Channels are bound to a group by48* specifying the group when constructing the channel. The associated thread49* pool is <em>owned</em> by the group; termination of the group results in the50* shutdown of the associated thread pool.51*52* <p> In addition to groups created explicitly, the Java virtual machine53* maintains a system-wide <em>default group</em> that is constructed54* automatically. Asynchronous channels that do not specify a group at55* construction time are bound to the default group. The default group has an56* associated thread pool that creates new threads as needed. The default group57* may be configured by means of system properties defined in the table below.58* Where the {@link java.util.concurrent.ThreadFactory ThreadFactory} for the59* default group is not configured then the pooled threads of the default group60* are {@link Thread#isDaemon daemon} threads.61*62* <table border summary="System properties">63* <tr>64* <th>System property</th>65* <th>Description</th>66* </tr>67* <tr>68* <td> {@code java.nio.channels.DefaultThreadPool.threadFactory} </td>69* <td> The value of this property is taken to be the fully-qualified name70* of a concrete {@link java.util.concurrent.ThreadFactory ThreadFactory}71* class. The class is loaded using the system class loader and instantiated.72* The factory's {@link java.util.concurrent.ThreadFactory#newThread73* newThread} method is invoked to create each thread for the default74* group's thread pool. If the process to load and instantiate the value75* of the property fails then an unspecified error is thrown during the76* construction of the default group. </td>77* </tr>78* <tr>79* <td> {@code java.nio.channels.DefaultThreadPool.initialSize} </td>80* <td> The value of the {@code initialSize} parameter for the default81* group (see {@link #withCachedThreadPool withCachedThreadPool}).82* The value of the property is taken to be the {@code String}83* representation of an {@code Integer} that is the initial size parameter.84* If the value cannot be parsed as an {@code Integer} it causes an85* unspecified error to be thrown during the construction of the default86* group. </td>87* </tr>88* </table>89*90* <a name="threading"></a><h2>Threading</h2>91*92* <p> The completion handler for an I/O operation initiated on a channel bound93* to a group is guaranteed to be invoked by one of the pooled threads in the94* group. This ensures that the completion handler is run by a thread with the95* expected <em>identity</em>.96*97* <p> Where an I/O operation completes immediately, and the initiating thread98* is one of the pooled threads in the group then the completion handler may99* be invoked directly by the initiating thread. To avoid stack overflow, an100* implementation may impose a limit as to the number of activations on the101* thread stack. Some I/O operations may prohibit invoking the completion102* handler directly by the initiating thread (see {@link103* AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}).104*105* <a name="shutdown"></a><h2>Shutdown and Termination</h2>106*107* <p> The {@link #shutdown() shutdown} method is used to initiate an <em>orderly108* shutdown</em> of a group. An orderly shutdown marks the group as shutdown;109* further attempts to construct a channel that binds to the group will throw110* {@link ShutdownChannelGroupException}. Whether or not a group is shutdown can111* be tested using the {@link #isShutdown() isShutdown} method. Once shutdown,112* the group <em>terminates</em> when all asynchronous channels that are bound to113* the group are closed, all actively executing completion handlers have run to114* completion, and resources used by the group are released. No attempt is made115* to stop or interrupt threads that are executing completion handlers. The116* {@link #isTerminated() isTerminated} method is used to test if the group has117* terminated, and the {@link #awaitTermination awaitTermination} method can be118* used to block until the group has terminated.119*120* <p> The {@link #shutdownNow() shutdownNow} method can be used to initiate a121* <em>forceful shutdown</em> of the group. In addition to the actions performed122* by an orderly shutdown, the {@code shutdownNow} method closes all open channels123* in the group as if by invoking the {@link AsynchronousChannel#close close}124* method.125*126* @since 1.7127*128* @see AsynchronousSocketChannel#open(AsynchronousChannelGroup)129* @see AsynchronousServerSocketChannel#open(AsynchronousChannelGroup)130*/131132public abstract class AsynchronousChannelGroup {133private final AsynchronousChannelProvider provider;134135/**136* Initialize a new instance of this class.137*138* @param provider139* The asynchronous channel provider for this group140*/141protected AsynchronousChannelGroup(AsynchronousChannelProvider provider) {142this.provider = provider;143}144145/**146* Returns the provider that created this channel group.147*148* @return The provider that created this channel group149*/150public final AsynchronousChannelProvider provider() {151return provider;152}153154/**155* Creates an asynchronous channel group with a fixed thread pool.156*157* <p> The resulting asynchronous channel group reuses a fixed number of158* threads. At any point, at most {@code nThreads} threads will be active159* processing tasks that are submitted to handle I/O events and dispatch160* completion results for operations initiated on asynchronous channels in161* the group.162*163* <p> The group is created by invoking the {@link164* AsynchronousChannelProvider#openAsynchronousChannelGroup(int,ThreadFactory)165* openAsynchronousChannelGroup(int,ThreadFactory)} method of the system-wide166* default {@link AsynchronousChannelProvider} object.167*168* @param nThreads169* The number of threads in the pool170* @param threadFactory171* The factory to use when creating new threads172*173* @return A new asynchronous channel group174*175* @throws IllegalArgumentException176* If {@code nThreads <= 0}177* @throws IOException178* If an I/O error occurs179*/180public static AsynchronousChannelGroup withFixedThreadPool(int nThreads,181ThreadFactory threadFactory)182throws IOException183{184return AsynchronousChannelProvider.provider()185.openAsynchronousChannelGroup(nThreads, threadFactory);186}187188/**189* Creates an asynchronous channel group with a given thread pool that190* creates new threads as needed.191*192* <p> The {@code executor} parameter is an {@code ExecutorService} that193* creates new threads as needed to execute tasks that are submitted to194* handle I/O events and dispatch completion results for operations initiated195* on asynchronous channels in the group. It may reuse previously constructed196* threads when they are available.197*198* <p> The {@code initialSize} parameter may be used by the implementation199* as a <em>hint</em> as to the initial number of tasks it may submit. For200* example, it may be used to indicate the initial number of threads that201* wait on I/O events.202*203* <p> The executor is intended to be used exclusively by the resulting204* asynchronous channel group. Termination of the group results in the205* orderly {@link ExecutorService#shutdown shutdown} of the executor206* service. Shutting down the executor service by other means results in207* unspecified behavior.208*209* <p> The group is created by invoking the {@link210* AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)211* openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide212* default {@link AsynchronousChannelProvider} object.213*214* @param executor215* The thread pool for the resulting group216* @param initialSize217* A value {@code >=0} or a negative value for implementation218* specific default219*220* @return A new asynchronous channel group221*222* @throws IOException223* If an I/O error occurs224*225* @see java.util.concurrent.Executors#newCachedThreadPool226*/227public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,228int initialSize)229throws IOException230{231return AsynchronousChannelProvider.provider()232.openAsynchronousChannelGroup(executor, initialSize);233}234235/**236* Creates an asynchronous channel group with a given thread pool.237*238* <p> The {@code executor} parameter is an {@code ExecutorService} that239* executes tasks submitted to dispatch completion results for operations240* initiated on asynchronous channels in the group.241*242* <p> Care should be taken when configuring the executor service. It243* should support <em>direct handoff</em> or <em>unbounded queuing</em> of244* submitted tasks, and the thread that invokes the {@link245* ExecutorService#execute execute} method should never invoke the task246* directly. An implementation may mandate additional constraints.247*248* <p> The executor is intended to be used exclusively by the resulting249* asynchronous channel group. Termination of the group results in the250* orderly {@link ExecutorService#shutdown shutdown} of the executor251* service. Shutting down the executor service by other means results in252* unspecified behavior.253*254* <p> The group is created by invoking the {@link255* AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)256* openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide257* default {@link AsynchronousChannelProvider} object with an {@code258* initialSize} of {@code 0}.259*260* @param executor261* The thread pool for the resulting group262*263* @return A new asynchronous channel group264*265* @throws IOException266* If an I/O error occurs267*/268public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)269throws IOException270{271return AsynchronousChannelProvider.provider()272.openAsynchronousChannelGroup(executor, 0);273}274275/**276* Tells whether or not this asynchronous channel group is shutdown.277*278* @return {@code true} if this asynchronous channel group is shutdown or279* has been marked for shutdown.280*/281public abstract boolean isShutdown();282283/**284* Tells whether or not this group has terminated.285*286* <p> Where this method returns {@code true}, then the associated thread287* pool has also {@link ExecutorService#isTerminated terminated}.288*289* @return {@code true} if this group has terminated290*/291public abstract boolean isTerminated();292293/**294* Initiates an orderly shutdown of the group.295*296* <p> This method marks the group as shutdown. Further attempts to construct297* channel that binds to this group will throw {@link ShutdownChannelGroupException}.298* The group terminates when all asynchronous channels in the group are299* closed, all actively executing completion handlers have run to completion,300* and all resources have been released. This method has no effect if the301* group is already shutdown.302*/303public abstract void shutdown();304305/**306* Shuts down the group and closes all open channels in the group.307*308* <p> In addition to the actions performed by the {@link #shutdown() shutdown}309* method, this method invokes the {@link AsynchronousChannel#close close}310* method on all open channels in the group. This method does not attempt to311* stop or interrupt threads that are executing completion handlers. The312* group terminates when all actively executing completion handlers have run313* to completion and all resources have been released. This method may be314* invoked at any time. If some other thread has already invoked it, then315* another invocation will block until the first invocation is complete,316* after which it will return without effect.317*318* @throws IOException319* If an I/O error occurs320*/321public abstract void shutdownNow() throws IOException;322323/**324* Awaits termination of the group.325326* <p> This method blocks until the group has terminated, or the timeout327* occurs, or the current thread is interrupted, whichever happens first.328*329* @param timeout330* The maximum time to wait, or zero or less to not wait331* @param unit332* The time unit of the timeout argument333*334* @return {@code true} if the group has terminated; {@code false} if the335* timeout elapsed before termination336*337* @throws InterruptedException338* If interrupted while waiting339*/340public abstract boolean awaitTermination(long timeout, TimeUnit unit)341throws InterruptedException;342}343344345