Java ServiceLoader源码分析

在上一篇文章:Java SPI(Service Provider Interface)简介 中对Java SPI机制做了简单说明,并附上了一个具体的demo。对Java SPI不熟悉的同学可以去参阅一下那篇文章,本文不再赘述。

本文将在上一篇文章的基础之上,结合JDK 1.7 源码来剖析Java SPI的内部实现原理。


在上一篇文章中,我们通过如下代码获取Service的具体实现,代码如下:

import java.util.Iterator;
import java.util.ServiceLoader;
import com.ricky.codelab.spi.DemoService;

//1.ServiceLoader.load
ServiceLoader<DemoService> serviceLoader = ServiceLoader.load(DemoService.class);

//2.serviceLoader.iterator()
Iterator<DemoService> it = serviceLoader.iterator();

//3.hasNext()
while (it.hasNext()) {
     //4.next()
     DemoService demoService = it.next();
}

1、ServiceLoader.load方法

首先来看看ServiceLoader.load方法,如下:

public static <S> ServiceLoader<S> load(Class<S> service) {
     ClassLoader cl = Thread.currentThread().getContextClassLoader();
     return ServiceLoader.load(service, cl);
}

它有一个重载方法,如下:

public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader){
    return new ServiceLoader<>(service, loader);
}

这里通过调用 new ServiceLoader<>(service, loader)返回一个ServiceLoader实例对象,ServiceLoader<>(service, loader)构造方法如下:

private ServiceLoader(Class<S> svc, ClassLoader cl) {
    service = svc;
    loader = cl;
    reload();
}

构造方法内部调用了reload方法,如下:

public void reload() {
    providers.clear();
    lookupIterator = new LazyIterator(service, loader);
}

providers、lookupIterator 属性定义如下:

// 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<>();

// The current lazy-lookup iterator
private LazyIterator lookupIterator;

接下来看看ServiceLoader内部类LazyIterator的实现代码,如下:

// Private inner class implementing fully-lazy provider lookup
//
private class LazyIterator
    implements Iterator<S>{

    Class<S> service;
    ClassLoader loader;
    Enumeration<URL> configs = null;
    Iterator<String> pending = null;
    String nextName = null;

    private LazyIterator(Class<S> service, ClassLoader loader) {
        this.service = service;
        this.loader = loader;
    }

    public boolean hasNext() {
        if (nextName != null) {
            return true;
        }
        if (configs == null) {
            try {
                String fullName = PREFIX + service.getName();
                if (loader == null)
                    configs = ClassLoader.getSystemResources(fullName);
                else
                    configs = loader.getResources(fullName);
            } catch (IOException x) {
                fail(service, "Error locating configuration files", x);
            }
        }
        while ((pending == null) || !pending.hasNext()) {
            if (!configs.hasMoreElements()) {
                return false;
            }
            pending = parse(service, configs.nextElement());
        }
        nextName = pending.next();
        return true;
    }

    public S next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        String cn = nextName;
        nextName = null;
        Class<?> c = null;
        try {
            c = Class.forName(cn, false, loader);
        } catch (ClassNotFoundException x) {
            fail(service,
                 "Provider " + cn + " not found");
        }
        if (!service.isAssignableFrom(c)) {
            fail(service,
                 "Provider " + cn  + " not a subtype");
        }
        try {
            S p = service.cast(c.newInstance());
            providers.put(cn, p);
            return p;
        } catch (Throwable x) {
            fail(service,
                 "Provider " + cn + " could not be instantiated",
                 x);
        }
        throw new Error();          // This cannot happen
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

}

其中,PREFIX 定义如下:

private static final String PREFIX = "META-INF/services/";

2、ServiceLoader iterator方法

当执行 Iterator it = serviceLoader.iterator(); 代码时,执行的是ServiceLoader iterator方法,代码如下:

public Iterator<S> iterator() {
    return new Iterator<S>() {

        Iterator<Map.Entry<String,S>> knownProviders
            = providers.entrySet().iterator();

        public boolean hasNext() {
            if (knownProviders.hasNext())
                return true;
            return lookupIterator.hasNext();
        }

        public S next() {
            if (knownProviders.hasNext())
                return knownProviders.next().getValue();
            return lookupIterator.next();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

    };
}

返回了一个Iterator的匿名类,

Iterator hasNext()方法

while (it.hasNext()) {
DemoService demoService = it.next();
}

it.hasNext()调用的是上述返回的 new Iterator()的public boolean hasNext()方法。

Iterator next方法

it.next();调用的是上述返回的 new Iterator()的public S next() 方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaServiceLoader是一个用于加载服务提供者的工具类。服务提供者是指实现了某个特定服务的类,它们通常会被打包成jar文件,并在应用程序运行时动态加载。 ServiceLoader的实现原理是基于Java SPI机制,它通过查找META-INF/services目录下的配置文件来加载服务提供者,配置文件的格式为: ``` com.example.MyService ``` 其中,com.example.MyService是服务提供者的全限定类名。 接下来,我们来分析一下ServiceLoader源码实现: 1. ServiceLoader的构造函数 ``` private ServiceLoader(Class<S> service, ClassLoader loader) { this.service = Objects.requireNonNull(service, "Service interface cannot be null"); this.loader = (loader == null) ? ClassLoader.getSystemClassLoader() : loader; acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null; reload(); } ``` 构造函数接收服务提供者的接口类和类加载器,然后进行初始化,并调用reload()方法加载服务提供者。 2. ServiceLoader的reload()方法 ``` private void reload() { providers.clear(); lookupIterator = new LazyIterator(service, loader); } ``` reload()方法会清空已加载的服务提供者,并创建一个新的LazyIterator对象。 3. ServiceLoader的iterator()方法 ``` public Iterator<S> iterator() { return new Iterator<S>() { private final LazyIterator<S> knownProviders = lookupIterator; private Iterator<S> serviceProviderIterator = Collections.emptyIterator(); public boolean hasNext() { if (serviceProviderIterator.hasNext()) { return true; } if (knownProviders.hasNext()) { serviceProviderIterator = knownProviders.next().iterator(); return hasNext(); } return false; } public S next() { if (!hasNext()) { throw new NoSuchElementException(); } return serviceProviderIterator.next(); } public void remove() { serviceProviderIterator.remove(); } }; } ``` iterator()方法会返回一个迭代器对象,用于遍历已加载的服务提供者。该迭代器内部维护了一个knownProviders对象和一个serviceProviderIterator对象。在遍历时,先判断serviceProviderIterator是否还有下一个元素,如果有则直接返回,否则就从knownProviders中加载下一个服务提供者,并将其迭代器赋值给serviceProviderIterator。 4. ServiceLoader的LazyIterator类 ``` private static class LazyIterator<T> implements Iterator<T> { Class<T> service; ClassLoader loader; Enumeration<URL> configs = null; Iterator<String> pending = null; String nextName = null; private LazyIterator(Class<T> service, ClassLoader loader) { this.service = service; this.loader = loader; } public boolean hasNext() { if (nextName != null) { return true; } if (configs == null) { try { String fullName = "META-INF/services/" + service.getName(); if (loader == null) { configs = ClassLoader.getSystemResources(fullName); } else { configs = loader.getResources(fullName); } } catch (IOException x) { fail(service, "Error locating configuration files", x); } } while (pending == null || !pending.hasNext()) { if (!configs.hasMoreElements()) { return false; } pending = parse(service, configs.nextElement()); } nextName = pending.next(); return true; } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } String cn = nextName; nextName = null; try { return service.cast(Class.forName(cn, true, loader).newInstance()); } catch (ClassNotFoundException x) { fail(service, "Provider " + cn + " not found"); } catch (Exception x) { fail(service, "Provider " + cn + " could not be instantiated", x); } throw new Error(); } public void remove() { throw new UnsupportedOperationException(); } } ``` LazyIterator类实现了Iterator接口,它负责从配置文件中解析出服务提供者的类名,并进行实例化。在hasNext()方法中,首先判断nextName是否已经被赋值,如果是则直接返回true,否则就从配置文件中解析出下一个类名。在next()方法中,将nextName赋值给cn变量,然后通过反射加载并实例化服务提供者类,最后返回实例化对象。 以上就是ServiceLoader源码实现分析。通过分析,我们可以了解到ServiceLoader的实现原理,以及如何通过配置文件来加载服务提供者。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值