Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load jars dynamically. I'm told there's a way of doing it by writing your own ClassLoader, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a jar file as its argument. Any suggestions for simple code that does this? P.S.: I kn...
What is the best way of searching the whole classpath for an annotated class? I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scann the whole classpath for certain annotation. Do you know a library or a Java facility to do this? Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or...
I am getting this message when I run my web application. It runs fine but I get this message during shutdown. SEVERE: A web application registered the JBDC driver [oracle.jdbc.driver.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. Any help appreciated.
How would you implement a Plugin-system for your Java application? Is it possible to have an easy to use (for the developer) system which achieves the following: Users put their plugins into a subdirectory of the app The Plugin can provide a configuration screen If you use a framework, is the license compatible with commercial developement?
I want to do something like this: List<Animal> animals = new ArrayList<Animal>(); for( Class c: list_of_all_classes_available_to_my_app() ) if (c is Anamal) animals.add( new c() ); So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This ...
What are the best practices for using ServiceLoader in an Environment with multiple ClassLoaders? The documentation recommends to create and save a single service instance at initialization: private static ServiceLoader<CodecSet> codecSetLoader = ServiceLoader.load(CodecSet.class); This would initialize the ServiceLoader using the current context classloader. Now suppose this snippet i...
Being someone who is allergic to dependencies, when would I use something like OSGi instead of the built in java 6 http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html (I want to let plugin jars just be dropped in). (FYI this is in a scala app, open to any suggestions, ServiceLoader is pretty damn close to what I want).
I am planning to use dependency injection framework. what should I choose? Guice or Spring? I will use java configuration both ways. also my application is pure java j2se, not web/j2ee application and I don't plan to use spring's rich capabilities. my main concern about guice is that it is much less popular and not in common use. I want a mature, documented and easy to use DI framework. Can you...
Okay guess this question looks a lot like: http://stackoverflow.com/questions/519422/what-is-the-best-way-to-replace-or-substitute-if-else-if-else-trees-in-programs consider this question CLOSED! I would like to refactor code which looks something like this: String input; // input from client socket. if (input.equals(x)) { doX(); } else if (input.equals(y)) { doY(); } else { unknown...
I have been working with JXTA 2.3 for the last year or so for a peer-to-peer computing platform I am developing. I am migrating to JXTA 2.5 and in the process I am trying to clean up a lot of my use of JXTA. For the most part, I approached JXTA with a "just make it work" attitude. I used it to jumpstart creating and managing my peer-to-peer overlay network and providing basic communication serv...
How do I discover classes at runtime in the classpath which implements a defined interface? ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.
I have a Java project that expects external modules to be registered with it. These modules: Implement a particular interface in the main project Are packaged into a uni-jar (along with any dependencies) Contain some human-readable meta-information (like the module name). My main project needs to be able to load at runtime (e.g. using its own classloader) any of these external modules. My q...
I get the ff. error in Java Console occassionally: Exception in thread "thread applet-my.package.MyApplet-10" java.lang.NoClassDefFoundError: another/package/SomeClass at my.package.MyApplet.init(MyApplet.java:95) at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: anot...
Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework. The largest issue I've found is it can be confusing for other developers who are just learning it. Also, I'd feel much better if it were a part of the language I was using. T...
Can I do it with reflection or something like that?
I'm currently wondering what the actual overhead, in the JVM, is for loading extra classes which are never used. We have code which iterates all the classes in the class path to find classes which implement a certain interface, we then load them. This allows custom classes to be simply dropped in a directory and they get loaded and registered. The side affect is that we hit every class in th...
I intend to develop a system that is entirely based on modules. The system base should have support for finding out about plugins, starting them up and being able to provide ways for those modules to communicate. Ideally, one should be able to put in new modules and yank out unused modules at will, and modules should be able to use each other's funcionality if it is available. This system shou...
I recently posted a question regarding a way to define the implementation of an abstract service on the client side. dfa mentioned java.util.ServiceLoader as a solution for my problem. I ended up going in a similar way, though not using ServiceLoader directly, mainly because i was using JDK 5. But another SOer jut went into panic when dfa mentioned ServiceLoader. I am wondering what are th...
I'm just new to annotations. I've created a sample annotationProcessor to handle my annotations and currently using command line script "-processor defaultproject.annotations.DefaultProcessor " to use it. is there any way to set this processor from inside the code? thanks a lot Moein
It seems like everybody has had an unpleasant brush with the Java Service Provider, that thing you can do with a file named like META-INF/services/com.example.Interface, but that nobody uses except for trying to load the right XML parser. I'm trying to work with a library that uses the Service Provider API, and trick it so that I can provide some runtime-extended classes (using cglib) that don...
I am writing an application that will ship in several different versions (initially around 10 variations of the code base will exist, and will need to be maintained). Of course, 98% or so of the code will be the same amongst the different systems, and it makes sense to keep the code base intact. My question is - what would be the preferred way to do this? If I for instance have a class (MyClas...
  /*
   * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;
 
 import java.net.URL;
 import java.util.List;
A simple service-provider loading facility.

A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.

For the purpose of loading, a service is represented by a single type, that is, a single interface or abstract class. (A concrete class can be used, but this is not recommended.) A provider of a given service contains one or more concrete classes that extend this service type with data and code specific to the provider. The provider class is typically not the entire provider itself but rather a proxy which contains enough information to decide whether the provider is able to satisfy a particular request together with code that can create the actual provider on demand. The details of provider classes tend to be highly service-specific; no single class or interface could possibly unify them, so no such type is defined here. The only requirement enforced by this facility is that provider classes must have a zero-argument constructor so that they can be instantiated during loading.

A service provider is identified by placing a provider-configuration file in the resource directory META-INF/services. The file's name is the fully-qualified binary name of the service's type. The file contains a list of fully-qualified binary names of concrete provider classes, one per line. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023', NUMBER SIGN); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8.

If a particular concrete provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates are ignored. The configuration file naming a particular provider need not be in the same jar file or other distribution unit as the provider itself. The provider must be accessible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.

Providers are located and instantiated lazily, that is, on demand. A service loader maintains a cache of the providers that have been loaded so far. Each invocation of the iterator method returns an iterator that first yields all of the elements of the cache, in instantiation order, and then lazily locates and instantiates any remaining providers, adding each one to the cache in turn. The cache can be cleared via the reload method.

Service loaders always execute in the security context of the caller. Trusted system code should typically invoke the methods in this class, and the methods of the iterators which they return, from within a privileged security context.

Instances of this class are not safe for use by multiple concurrent threads.

Unless otherwise specified, passing a null argument to any method in this class will cause a java.lang.NullPointerException to be thrown.

Example Suppose we have a service type com.example.CodecSet which is intended to represent sets of encoder/decoder pairs for some protocol. In this case it is an abstract class with two abstract methods:

 public abstract Encoder getEncoder(String encodingName);
 public abstract Decoder getDecoder(String encodingName);
Each method returns an appropriate object or null if the provider does not support the given encoding. Typical providers support more than one encoding.

If com.example.impl.StandardCodecs is an implementation of the CodecSet service then its jar file also contains a file named

 META-INF/services/com.example.CodecSet

This file contains the single line:

 com.example.impl.StandardCodecs    # Standard codecs

The CodecSet class creates and saves a single service instance at initialization:

 private static ServiceLoader<CodecSet> codecSetLoader
     = ServiceLoader.load(CodecSet.class);

To locate an encoder for a given encoding name it defines a static factory method which iterates through the known and available providers, returning only when it has located a suitable encoder or has run out of providers.

 public static Encoder getEncoder(String encodingName) {
     for (CodecSet cp : codecSetLoader) {
         Encoder enc = cp.getEncoder(encodingName);
         if (enc != null)
             return enc;
     }
     return null;
 }

A getDecoder method is defined similarly.

Usage Note If the class path of a class loader that is used for provider loading includes remote network URLs then those URLs will be dereferenced in the process of searching for provider-configuration files.

This activity is normal, although it may cause puzzling entries to be created in web-server logs. If a web server is not configured correctly, however, then this activity may cause the provider-loading algorithm to fail spuriously.

A web server should return an HTTP 404 (Not Found) response when a requested resource does not exist. Sometimes, however, web servers are erroneously configured to return an HTTP 200 (OK) response along with a helpful HTML error page in such cases. This will cause a ServiceConfigurationError to be thrown when this class attempts to parse the HTML page as a provider-configuration file. The best solution to this problem is to fix the misconfigured web server to return the correct response code (HTTP 404) along with the HTML error page.

Parameters:
<S> The type of the service to be loaded by this loader
Author(s):
Mark Reinhold
Since:
1.6

public final class ServiceLoader<S>
    implements Iterable<S>
    private static final String PREFIX = "META-INF/services/";
    // The class or interface representing the service being loaded
    private Class<S> service;
    // The class loader used to locate, load, and instantiate providers
    private ClassLoader loader;
    // Cached providers, in instantiation order
    private LinkedHashMap<String,S> providers = new LinkedHashMap<String,S>();
    // The current lazy-lookup iterator
    private LazyIterator lookupIterator;

    
Clear this loader's provider cache so that all providers will be reloaded.

After invoking this method, subsequent invocations of the iterator() method will lazily look up and instantiate providers from scratch, just as is done by a newly-created loader.

This method is intended for use in situations in which new providers can be installed into a running Java virtual machine.

    public void reload() {
        .clear();
         = new LazyIterator();
    }
    private ServiceLoader(Class<S> svcClassLoader cl) {
         = svc;
         = cl;
        reload();
    }
    private static void fail(Class serviceString msgThrowable cause)
        throws ServiceConfigurationError
    {
        throw new ServiceConfigurationError(service.getName() + ": " + msg,
                                            cause);
    }
    private static void fail(Class serviceString msg)
        throws ServiceConfigurationError
    {
        throw new ServiceConfigurationError(service.getName() + ": " + msg);
    }
    private static void fail(Class serviceURL uint lineString msg)
        throws ServiceConfigurationError
    {
        fail(serviceu + ":" + line + ": " + msg);
    }
    // Parse a single line from the given configuration file, adding the name
    // on the line to the names list.
    //
    private int parseLine(Class serviceURL uBufferedReader rint lc,
                          List<Stringnames)
        throws IOExceptionServiceConfigurationError
    {
        String ln = r.readLine();
        if (ln == null) {
            return -1;
        }
        int ci = ln.indexOf('#');
        if (ci >= 0) ln = ln.substring(0, ci);
        ln = ln.trim();
        int n = ln.length();
        if (n != 0) {
            if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
                fail(serviceulc"Illegal configuration-file syntax");
            int cp = ln.codePointAt(0);
            if (!Character.isJavaIdentifierStart(cp))
                fail(serviceulc"Illegal provider-class name: " + ln);
            for (int i = Character.charCount(cp); i < ni += Character.charCount(cp)) {
                cp = ln.codePointAt(i);
                if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
                    fail(serviceulc"Illegal provider-class name: " + ln);
            }
            if (!.containsKey(ln) && !names.contains(ln))
                names.add(ln);
        }
        return lc + 1;
    }
    // Parse the content of the given URL as a provider-configuration file.
    //
    // @param  service
    //         The service type for which providers are being sought;
    //         used to construct error detail strings
    //
    // @param  u
    //         The URL naming the configuration file to be parsed
    //
    // @return A (possibly empty) iterator that will yield the provider-class
    //         names in the given configuration file that are not yet members
    //         of the returned set
    //
    // @throws ServiceConfigurationError
    //         If an I/O error occurs while reading from the given URL, or
    //         if a configuration-file format error is detected
    //
    private Iterator<Stringparse(Class serviceURL u)
        throws ServiceConfigurationError
    {
        InputStream in = null;
        BufferedReader r = null;
        ArrayList<Stringnames = new ArrayList<String>();
        try {
            in = u.openStream();
            r = new BufferedReader(new InputStreamReader(in"utf-8"));
            int lc = 1;
            while ((lc = parseLine(serviceurlcnames)) >= 0);
        } catch (IOException x) {
            fail(service"Error reading configuration file"x);
        } finally {
            try {
                if (r != nullr.close();
                if (in != nullin.close();
            } catch (IOException y) {
                fail(service"Error closing configuration file"y);
            }
        }
        return names.iterator();
    }
    // Private inner class implementing fully-lazy provider lookup
    //
    private class LazyIterator
        implements Iterator<S>
    {
        Class<S> service;
        ClassLoader loader;
        Enumeration<URLconfigs = null;
        Iterator<Stringpending = null;
        String nextName = null;
        private LazyIterator(Class<S> serviceClassLoader loader) {
            this. = service;
            this. = loader;
        }
        public boolean hasNext() {
            if ( != null) {
                return true;
            }
            if ( == null) {
                try {
                    String fullName =  + .getName();
                    if ( == null)
                         = ClassLoader.getSystemResources(fullName);
                    else
                         = .getResources(fullName);
                } catch (IOException x) {
                    fail("Error locating configuration files"x);
                }
            }
            while (( == null) || !.hasNext()) {
                if (!.hasMoreElements()) {
                    return false;
                }
                 = parse(.nextElement());
            }
             = .next();
            return true;
        }
        public S next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            String cn = ;
             = null;
            try {
                S p = .cast(Class.forName(cntrue)
                                   .newInstance());
                .put(cnp);
                return p;
            } catch (ClassNotFoundException x) {
                fail(,
                     "Provider " + cn + " not found");
            } catch (Throwable x) {
                fail(,
                     "Provider " + cn + " could not be instantiated: " + x,
                     x);
            }
            throw new Error();          // This cannot happen
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    
Lazily loads the available providers of this loader's service.

The iterator returned by this method first yields all of the elements of the provider cache, in instantiation order. It then lazily loads and instantiates any remaining providers, adding each one to the cache in turn.

To achieve laziness the actual work of parsing the available provider-configuration files and instantiating providers must be done by the iterator itself. Its hasNext and next methods can therefore throw a ServiceConfigurationError if a provider-configuration file violates the specified format, or if it names a provider class that cannot be found and instantiated, or if the result of instantiating the class is not assignable to the service type, or if any other kind of exception or error is thrown as the next provider is located and instantiated. To write robust code it is only necessary to catch ServiceConfigurationError when using a service iterator.

If such an error is thrown then subsequent invocations of the iterator will make a best effort to locate and instantiate the next available provider, but in general such recovery cannot be guaranteed.

Design Note Throwing an error in these cases may seem extreme. The rationale for this behavior is that a malformed provider-configuration file, like a malformed class file, indicates a serious problem with the way the Java virtual machine is configured or is being used. As such it is preferable to throw an error rather than try to recover or, even worse, fail silently.

The iterator returned by this method does not support removal. Invoking its remove method will cause an java.lang.UnsupportedOperationException to be thrown.

Returns:
An iterator that lazily loads providers for this loader's service
    public Iterator<S> iterator() {
        return new Iterator<S>() {
            Iterator<Map.Entry<String,S>> knownProviders
                = .entrySet().iterator();
            public boolean hasNext() {
                if (.hasNext())
                    return true;
                return .hasNext();
            }
            public S next() {
                if (.hasNext())
                    return .next().getValue();
                return .next();
            }
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    
Creates a new service loader for the given service type and class loader.

Parameters:
service The interface or abstract class representing the service
loader The class loader to be used to load provider-configuration files and provider classes, or null if the system class loader (or, failing that, the bootstrap class loader) is to be used
Returns:
A new service loader
    public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader)
    {
        return new ServiceLoader<S>(serviceloader);
    }

    
Creates a new service loader for the given service type, using the current thread's context class loader.

An invocation of this convenience method of the form

 ServiceLoader.load(service)
is equivalent to
 ServiceLoader.load(service,
                    Thread.currentThread().getContextClassLoader())

Parameters:
service The interface or abstract class representing the service
Returns:
A new service loader
    public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(servicecl);
    }

    
Creates a new service loader for the given service type, using the extension class loader.

This convenience method simply locates the extension class loader, call it extClassLoader, and then returns

 ServiceLoader.load(service, extClassLoader)

If the extension class loader cannot be found then the system class loader is used; if there is no system class loader then the bootstrap class loader is used.

This method is intended for use when only installed providers are desired. The resulting service will only find and load providers that have been installed into the current Java virtual machine; providers on the application's class path will be ignored.

Parameters:
service The interface or abstract class representing the service
Returns:
A new service loader
    public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        ClassLoader prev = null;
        while (cl != null) {
            prev = cl;
            cl = cl.getParent();
        }
        return ServiceLoader.load(serviceprev);
    }

    
Returns a string describing this service.

Returns:
A descriptive string
    public String toString() {
        return "java.util.ServiceLoader[" + .getName() + "]";
    }
New to GrepCode? Check out our FAQ X