Skip to content

Commit e9b9698

Browse files
committed
Add centralized service loader utility
This allows library consumers to control the classloader in applications with non-trivial classloading requirements.
1 parent 97fe851 commit e9b9698

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package ucar.nc2.util;
2+
3+
import java.util.ServiceLoader;
4+
5+
/**
6+
* Centralized access to the jdk's built in {@link ServiceLoader} utility to support using the NetCDF library in
7+
* applications with non-trivial class loading requirements.
8+
*/
9+
public class NcServiceLoader {
10+
11+
private static ClassLoader classLoader;
12+
13+
public static <S> ServiceLoader<S> load(Class<S> service) {
14+
ClassLoader useClassLoader;
15+
16+
if (classLoader == null) {
17+
useClassLoader = Thread.currentThread().getContextClassLoader();
18+
} else {
19+
useClassLoader = classLoader;
20+
}
21+
22+
return ServiceLoader.load(service, useClassLoader);
23+
}
24+
25+
/**
26+
* Services will be loaded using whatever happens to be the current thread's context class loader at the time
27+
* services are loaded. This is the default behaviour and will work for applications that use the NetCDF library
28+
* without any special class-loading requirements.
29+
*/
30+
public static void useContextClassLoader() {
31+
classLoader = null;
32+
}
33+
34+
/**
35+
* Services will be loaded using the same classloader that loaded this class, assumed to be
36+
* the same one that will load the rest of the netcdf library. This option is suitable for applications that
37+
* use only the built-in functionality, i.e they do not extend the library via the {@link ServiceLoader} mechanism
38+
*/
39+
public static void usePackageClassLoader() {
40+
classLoader = NcServiceLoader.class.getClassLoader();
41+
}
42+
43+
/**
44+
* Services will be loaded using a specific custom class loader. This class loader should 'descend' from the one that
45+
* loaded the NetCDF library code, otherwise any services loaded are likely to throw {@link ClassCastException}s
46+
*/
47+
public static void useCustomClassLoader(ClassLoader useClassLoader) {
48+
classLoader = useClassLoader;
49+
}
50+
}

0 commit comments

Comments
 (0)