All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.hippo4j.starter.spi.DynamicTpServiceLoader Maven / Gradle / Ivy

There is a newer version: 1.5.0
Show newest version
package cn.hippo4j.starter.spi;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Dynamic threadPool service loader.
 *
 * @author chen.ma
 * @date 2021/7/10 23:45
 */
public class DynamicTpServiceLoader {

    private static final Map, Collection> SERVICES = new ConcurrentHashMap();

    public static void register(final Class serviceInterface) {
        if (!SERVICES.containsKey(serviceInterface)) {
            SERVICES.put(serviceInterface, load(serviceInterface));
        }
    }

    private static  Collection load(final Class serviceInterface) {
        Collection result = new LinkedList<>();
        for (T each : ServiceLoader.load(serviceInterface)) {
            result.add(each);
        }
        return result;
    }

    public static  Collection getSingletonServiceInstances(final Class service) {
        return (Collection) SERVICES.getOrDefault(service, Collections.emptyList());
    }

    public static  Collection newServiceInstances(final Class service) {
        return SERVICES.containsKey(service) ? SERVICES.get(service).stream().map(each -> (T) newServiceInstance(each.getClass())).collect(Collectors.toList()) : Collections.emptyList();
    }

    private static Object newServiceInstance(final Class clazz) {
        try {
            return clazz.newInstance();
        } catch (final InstantiationException | IllegalAccessException ex) {
            throw new ServiceLoaderInstantiationException(clazz, ex);
        }
    }

}