Path: blob/master/src/java.base/share/classes/java/nio/channels/AsynchronousChannelGroup.java
41159 views
/*1* Copyright (c) 2007, 2020, 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 class="striped">63* <caption style="display:none:">System properties</caption>64* <thead>65* <tr>66* <th scope="col">System property</th>67* <th scope="col">Description</th>68* </tr>69* </thead>70* <tbody>71* <tr>72* <th scope="row">73* {@systemProperty java.nio.channels.DefaultThreadPool.threadFactory}74* </th>75* <td> The value of this property is taken to be the fully-qualified name76* of a concrete {@link java.util.concurrent.ThreadFactory ThreadFactory}77* class. The class is loaded using the system class loader and instantiated.78* The factory's {@link java.util.concurrent.ThreadFactory#newThread79* newThread} method is invoked to create each thread for the default80* group's thread pool. If the process to load and instantiate the value81* of the property fails then an unspecified error is thrown during the82* construction of the default group. </td>83* </tr>84* <tr>85* <th scope="row">86* {@systemProperty java.nio.channels.DefaultThreadPool.initialSize}87* </th>88* <td> The value of the {@code initialSize} parameter for the default89* group (see {@link #withCachedThreadPool withCachedThreadPool}).90* The value of the property is taken to be the {@code String}91* representation of an {@code Integer} that is the initial size parameter.92* If the value cannot be parsed as an {@code Integer} it causes an93* unspecified error to be thrown during the construction of the default94* group. </td>95* </tr>96* </tbody>97* </table>98*99* <a id="threading"></a><h2>Threading</h2>100*101* <p> The completion handler for an I/O operation initiated on a channel bound102* to a group is guaranteed to be invoked by one of the pooled threads in the103* group. This ensures that the completion handler is run by a thread with the104* expected <em>identity</em>.105*106* <p> Where an I/O operation completes immediately, and the initiating thread107* is one of the pooled threads in the group then the completion handler may108* be invoked directly by the initiating thread. To avoid stack overflow, an109* implementation may impose a limit as to the number of activations on the110* thread stack. Some I/O operations may prohibit invoking the completion111* handler directly by the initiating thread (see {@link112* AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}).113*114* <a id="shutdown"></a><h2>Shutdown and Termination</h2>115*116* <p> The {@link #shutdown() shutdown} method is used to initiate an <em>orderly117* shutdown</em> of a group. An orderly shutdown marks the group as shutdown;118* further attempts to construct a channel that binds to the group will throw119* {@link ShutdownChannelGroupException}. Whether or not a group is shutdown can120* be tested using the {@link #isShutdown() isShutdown} method. Once shutdown,121* the group <em>terminates</em> when all asynchronous channels that are bound to122* the group are closed, all actively executing completion handlers have run to123* completion, and resources used by the group are released. No attempt is made124* to stop or interrupt threads that are executing completion handlers. The125* {@link #isTerminated() isTerminated} method is used to test if the group has126* terminated, and the {@link #awaitTermination awaitTermination} method can be127* used to block until the group has terminated.128*129* <p> The {@link #shutdownNow() shutdownNow} method can be used to initiate a130* <em>forceful shutdown</em> of the group. In addition to the actions performed131* by an orderly shutdown, the {@code shutdownNow} method closes all open channels132* in the group as if by invoking the {@link AsynchronousChannel#close close}133* method.134*135* @since 1.7136*137* @see AsynchronousSocketChannel#open(AsynchronousChannelGroup)138* @see AsynchronousServerSocketChannel#open(AsynchronousChannelGroup)139*/140141public abstract class AsynchronousChannelGroup {142private final AsynchronousChannelProvider provider;143144/**145* Initialize a new instance of this class.146*147* @param provider148* The asynchronous channel provider for this group149*/150protected AsynchronousChannelGroup(AsynchronousChannelProvider provider) {151this.provider = provider;152}153154/**155* Returns the provider that created this channel group.156*157* @return The provider that created this channel group158*/159public final AsynchronousChannelProvider provider() {160return provider;161}162163/**164* Creates an asynchronous channel group with a fixed thread pool.165*166* <p> The resulting asynchronous channel group reuses a fixed number of167* threads. At any point, at most {@code nThreads} threads will be active168* processing tasks that are submitted to handle I/O events and dispatch169* completion results for operations initiated on asynchronous channels in170* the group.171*172* <p> The group is created by invoking the {@link173* AsynchronousChannelProvider#openAsynchronousChannelGroup(int,ThreadFactory)174* openAsynchronousChannelGroup(int,ThreadFactory)} method of the system-wide175* default {@link AsynchronousChannelProvider} object.176*177* @param nThreads178* The number of threads in the pool179* @param threadFactory180* The factory to use when creating new threads181*182* @return A new asynchronous channel group183*184* @throws IllegalArgumentException185* If {@code nThreads <= 0}186* @throws IOException187* If an I/O error occurs188*/189public static AsynchronousChannelGroup withFixedThreadPool(int nThreads,190ThreadFactory threadFactory)191throws IOException192{193return AsynchronousChannelProvider.provider()194.openAsynchronousChannelGroup(nThreads, threadFactory);195}196197/**198* Creates an asynchronous channel group with a given thread pool that199* creates new threads as needed.200*201* <p> The {@code executor} parameter is an {@code ExecutorService} that202* creates new threads as needed to execute tasks that are submitted to203* handle I/O events and dispatch completion results for operations initiated204* on asynchronous channels in the group. It may reuse previously constructed205* threads when they are available.206*207* <p> The {@code initialSize} parameter may be used by the implementation208* as a <em>hint</em> as to the initial number of tasks it may submit. For209* example, it may be used to indicate the initial number of threads that210* wait on I/O events.211*212* <p> The executor is intended to be used exclusively by the resulting213* asynchronous channel group. Termination of the group results in the214* orderly {@link ExecutorService#shutdown shutdown} of the executor215* service. Shutting down the executor service by other means results in216* unspecified behavior.217*218* <p> The group is created by invoking the {@link219* AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)220* openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide221* default {@link AsynchronousChannelProvider} object.222*223* @param executor224* The thread pool for the resulting group225* @param initialSize226* A value {@code >=0} or a negative value for implementation227* specific default228*229* @return A new asynchronous channel group230*231* @throws IOException232* If an I/O error occurs233*234* @see java.util.concurrent.Executors#newCachedThreadPool235*/236public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,237int initialSize)238throws IOException239{240return AsynchronousChannelProvider.provider()241.openAsynchronousChannelGroup(executor, initialSize);242}243244/**245* Creates an asynchronous channel group with a given thread pool.246*247* <p> The {@code executor} parameter is an {@code ExecutorService} that248* executes tasks submitted to dispatch completion results for operations249* initiated on asynchronous channels in the group.250*251* <p> Care should be taken when configuring the executor service. It252* should support <em>direct handoff</em> or <em>unbounded queuing</em> of253* submitted tasks, and the thread that invokes the {@link254* ExecutorService#execute execute} method should never invoke the task255* directly. An implementation may mandate additional constraints.256*257* <p> The executor is intended to be used exclusively by the resulting258* asynchronous channel group. Termination of the group results in the259* orderly {@link ExecutorService#shutdown shutdown} of the executor260* service. Shutting down the executor service by other means results in261* unspecified behavior.262*263* <p> The group is created by invoking the {@link264* AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)265* openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide266* default {@link AsynchronousChannelProvider} object with an {@code267* initialSize} of {@code 0}.268*269* @param executor270* The thread pool for the resulting group271*272* @return A new asynchronous channel group273*274* @throws IOException275* If an I/O error occurs276*/277public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)278throws IOException279{280return AsynchronousChannelProvider.provider()281.openAsynchronousChannelGroup(executor, 0);282}283284/**285* Tells whether or not this asynchronous channel group is shutdown.286*287* @return {@code true} if this asynchronous channel group is shutdown or288* has been marked for shutdown.289*/290public abstract boolean isShutdown();291292/**293* Tells whether or not this group has terminated.294*295* <p> Where this method returns {@code true}, then the associated thread296* pool has also {@link ExecutorService#isTerminated terminated}.297*298* @return {@code true} if this group has terminated299*/300public abstract boolean isTerminated();301302/**303* Initiates an orderly shutdown of the group.304*305* <p> This method marks the group as shutdown. Further attempts to construct306* channel that binds to this group will throw {@link ShutdownChannelGroupException}.307* The group terminates when all asynchronous channels in the group are308* closed, all actively executing completion handlers have run to completion,309* and all resources have been released. This method has no effect if the310* group is already shutdown.311*/312public abstract void shutdown();313314/**315* Shuts down the group and closes all open channels in the group.316*317* <p> In addition to the actions performed by the {@link #shutdown() shutdown}318* method, this method invokes the {@link AsynchronousChannel#close close}319* method on all open channels in the group. This method does not attempt to320* stop or interrupt threads that are executing completion handlers. The321* group terminates when all actively executing completion handlers have run322* to completion and all resources have been released. This method may be323* invoked at any time. If some other thread has already invoked it, then324* another invocation will block until the first invocation is complete,325* after which it will return without effect.326*327* @throws IOException328* If an I/O error occurs329*/330public abstract void shutdownNow() throws IOException;331332/**333* Awaits termination of the group.334*335* <p> This method blocks until the group has terminated, or the timeout336* occurs, or the current thread is interrupted, whichever happens first.337*338* @param timeout339* The maximum time to wait, or zero or less to not wait340* @param unit341* The time unit of the timeout argument342*343* @return {@code true} if the group has terminated; {@code false} if the344* timeout elapsed before termination345*346* @throws InterruptedException347* If interrupted while waiting348*/349public abstract boolean awaitTermination(long timeout, TimeUnit unit)350throws InterruptedException;351}352353354