Class ServiceLoaderUtil


  • @InternalApi
    public final class ServiceLoaderUtil
    extends java.lang.Object
    An utility class to retrieve services in a safe way.

    This class should be considered internal.

    A common source of ServiceLoader failures, when running in a multi-classloader environment, is the presence of multiple classes with the same class name in the same classloader hierarchy. Since ServiceLoader retrieves services by class name, it is entirely possible that the registered services don't extend the required interface and cause an exception to be thrown by ServiceLoader.

    The purpose of this class is to:

    1. skip faulty services, allowing for a partial retrieval of the good ones,
    2. allow to integrate other sources of services like OSGi services.
    Since:
    2.18.0
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private static int MAX_BROKEN_SERVICES  
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      private ServiceLoaderUtil()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <S> java.util.stream.Stream<S> safeStream​(java.lang.Class<S> serviceType, java.util.ServiceLoader<? extends S> serviceLoader, Logger logger)
      Retrieves services registered with ServiceLoader
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • ServiceLoaderUtil

        private ServiceLoaderUtil()
    • Method Detail

      • safeStream

        public static <S> java.util.stream.Stream<S> safeStream​(java.lang.Class<S> serviceType,
                                                                java.util.ServiceLoader<? extends S> serviceLoader,
                                                                Logger logger)
        Retrieves services registered with ServiceLoader

        It ignores the most common service loading errors.

        Parameters:
        serviceType - The service type to use for OSGi service retrieval.
        serviceLoader - The service loader instance to use.
        logger - The logger to use to report service failures.
        Returns:
        A stream of all correctly loaded services.
        Since:
        2.24.0