Java ServiceLoader源碼分析__Java

來源:互聯網
上載者:User

在上一篇文章: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.loadServiceLoader<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 providersprivate ClassLoader loader;// Cached providers, in instantiation orderprivate LinkedHashMap<String,S> providers = new LinkedHashMap<>();// The current lazy-lookup iteratorprivate 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() 方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.