1 /*
2  * Copyright (c) 2007, 2013, 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.spi;
27 
28 import java.nio.channels.*;
29 import java.io.IOException;
30 import java.util.Iterator;
31 import java.util.ServiceLoader;
32 import java.util.ServiceConfigurationError;
33 import java.util.concurrent.*;
34 import java.security.AccessController;
35 import java.security.PrivilegedAction;
36 
37 /**
38  * Service-provider class for asynchronous channels.
39  *
40  * <p> An asynchronous channel provider is a concrete subclass of this class that
41  * has a zero-argument constructor and implements the abstract methods specified
42  * below.  A given invocation of the Java virtual machine maintains a single
43  * system-wide default provider instance, which is returned by the {@link
44  * #provider() provider} method.  The first invocation of that method will locate
45  * the default provider as specified below.
46  *
47  * <p> All of the methods in this class are safe for use by multiple concurrent
48  * threads.  </p>
49  *
50  * @since 1.7
51  */
52 
53 public abstract class AsynchronousChannelProvider {
checkPermission()54     private static Void checkPermission() {
55         SecurityManager sm = System.getSecurityManager();
56         if (sm != null)
57             sm.checkPermission(new RuntimePermission("asynchronousChannelProvider"));
58         return null;
59     }
AsynchronousChannelProvider(Void ignore)60     private AsynchronousChannelProvider(Void ignore) { }
61 
62     /**
63      * Initializes a new instance of this class.
64      *
65      * @throws  SecurityException
66      *          If a security manager has been installed and it denies
67      *          {@link RuntimePermission}<tt>("asynchronousChannelProvider")</tt>
68      */
AsynchronousChannelProvider()69     protected AsynchronousChannelProvider() {
70         this(checkPermission());
71     }
72 
73     // lazy initialization of default provider
74     private static class ProviderHolder {
75         static final AsynchronousChannelProvider provider = load();
76 
load()77         private static AsynchronousChannelProvider load() {
78             return AccessController
79                 .doPrivileged(new PrivilegedAction<AsynchronousChannelProvider>() {
80                     public AsynchronousChannelProvider run() {
81                         AsynchronousChannelProvider p;
82                         p = loadProviderFromProperty();
83                         if (p != null)
84                             return p;
85                         p = loadProviderAsService();
86                         if (p != null)
87                             return p;
88                         return sun.nio.ch.DefaultAsynchronousChannelProvider.create();
89                     }});
90         }
91 
loadProviderFromProperty()92         private static AsynchronousChannelProvider loadProviderFromProperty() {
93             String cn = System.getProperty("java.nio.channels.spi.AsynchronousChannelProvider");
94             if (cn == null)
95                 return null;
96             try {
97                 Class<?> c = Class.forName(cn, true,
98                                            ClassLoader.getSystemClassLoader());
99                 return (AsynchronousChannelProvider)c.newInstance();
100             } catch (ClassNotFoundException x) {
101                 throw new ServiceConfigurationError(null, x);
102             } catch (IllegalAccessException x) {
103                 throw new ServiceConfigurationError(null, x);
104             } catch (InstantiationException x) {
105                 throw new ServiceConfigurationError(null, x);
106             } catch (SecurityException x) {
107                 throw new ServiceConfigurationError(null, x);
108             }
109         }
110 
loadProviderAsService()111         private static AsynchronousChannelProvider loadProviderAsService() {
112             ServiceLoader<AsynchronousChannelProvider> sl =
113                 ServiceLoader.load(AsynchronousChannelProvider.class,
114                                    ClassLoader.getSystemClassLoader());
115             Iterator<AsynchronousChannelProvider> i = sl.iterator();
116             for (;;) {
117                 try {
118                     return (i.hasNext()) ? i.next() : null;
119                 } catch (ServiceConfigurationError sce) {
120                     if (sce.getCause() instanceof SecurityException) {
121                         // Ignore the security exception, try the next provider
122                         continue;
123                     }
124                     throw sce;
125                 }
126             }
127         }
128     }
129 
130     /**
131      * Returns the system-wide default asynchronous channel provider for this
132      * invocation of the Java virtual machine.
133      *
134      * <p> The first invocation of this method locates the default provider
135      * object as follows: </p>
136      *
137      * <ol>
138      *
139      *   <li><p> If the system property
140      *   <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> is defined
141      *   then it is taken to be the fully-qualified name of a concrete provider class.
142      *   The class is loaded and instantiated; if this process fails then an
143      *   unspecified error is thrown.  </p></li>
144      *
145      *   <li><p> If a provider class has been installed in a jar file that is
146      *   visible to the system class loader, and that jar file contains a
147      *   provider-configuration file named
148      *   <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> in the resource
149      *   directory <tt>META-INF/services</tt>, then the first class name
150      *   specified in that file is taken.  The class is loaded and
151      *   instantiated; if this process fails then an unspecified error is
152      *   thrown.  </p></li>
153      *
154      *   <li><p> Finally, if no provider has been specified by any of the above
155      *   means then the system-default provider class is instantiated and the
156      *   result is returned.  </p></li>
157      *
158      * </ol>
159      *
160      * <p> Subsequent invocations of this method return the provider that was
161      * returned by the first invocation.  </p>
162      *
163      * @return  The system-wide default AsynchronousChannel provider
164      */
165     public static AsynchronousChannelProvider provider() {
166         return ProviderHolder.provider;
167     }
168 
169     /**
170      * Constructs a new asynchronous channel group with a fixed thread pool.
171      *
172      * @param   nThreads
173      *          The number of threads in the pool
174      * @param   threadFactory
175      *          The factory to use when creating new threads
176      *
177      * @return  A new asynchronous channel group
178      *
179      * @throws  IllegalArgumentException
180      *          If {@code nThreads <= 0}
181      * @throws  IOException
182      *          If an I/O error occurs
183      *
184      * @see AsynchronousChannelGroup#withFixedThreadPool
185      */
186     public abstract AsynchronousChannelGroup
187         openAsynchronousChannelGroup(int nThreads, ThreadFactory threadFactory) throws IOException;
188 
189     /**
190      * Constructs a new asynchronous channel group with the given thread pool.
191      *
192      * @param   executor
193      *          The thread pool
194      * @param   initialSize
195      *          A value {@code >=0} or a negative value for implementation
196      *          specific default
197      *
198      * @return  A new asynchronous channel group
199      *
200      * @throws  IOException
201      *          If an I/O error occurs
202      *
203      * @see AsynchronousChannelGroup#withCachedThreadPool
204      */
205     public abstract AsynchronousChannelGroup
206         openAsynchronousChannelGroup(ExecutorService executor, int initialSize) throws IOException;
207 
208     /**
209      * Opens an asynchronous server-socket channel.
210      *
211      * @param   group
212      *          The group to which the channel is bound, or {@code null} to
213      *          bind to the default group
214      *
215      * @return  The new channel
216      *
217      * @throws  IllegalChannelGroupException
218      *          If the provider that created the group differs from this provider
219      * @throws  ShutdownChannelGroupException
220      *          The group is shutdown
221      * @throws  IOException
222      *          If an I/O error occurs
223      */
224     public abstract AsynchronousServerSocketChannel openAsynchronousServerSocketChannel
225         (AsynchronousChannelGroup group) throws IOException;
226 
227     /**
228      * Opens an asynchronous socket channel.
229      *
230      * @param   group
231      *          The group to which the channel is bound, or {@code null} to
232      *          bind to the default group
233      *
234      * @return  The new channel
235      *
236      * @throws  IllegalChannelGroupException
237      *          If the provider that created the group differs from this provider
238      * @throws  ShutdownChannelGroupException
239      *          The group is shutdown
240      * @throws  IOException
241      *          If an I/O error occurs
242      */
243     public abstract AsynchronousSocketChannel openAsynchronousSocketChannel
244         (AsynchronousChannelGroup group) throws IOException;
245 }
246