• java
  • go
  • 数据库
  • linux
  • 中间件
  • 书
  • 源码
  • 夕拾

  • java
  • go
  • 数据库
  • linux
  • 中间件
  • 书
  • 源码
  • 夕拾

java spi及原理

目录

  • 目录
  • 源码
    • lazy迭代器
  • dubbo的spi

spi核心其实也很简单….spi全名即

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
// load的时候调用此构造器
private ServiceLoader(Class<S> svc, ClassLoader cl) {
// 传入的api
service = Objects.requireNonNull(svc, "Service interface cannot be null");
// 类加载器
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
//
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
reload();
}

//
public void reload() {
// 清空缓存(provider是一个map)
providers.clear();
lookupIterator = new LazyIterator(service, loader);
}

lazy迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 S next() {
if (acc == null) {
return nextService();
} else {
PrivilegedAction<S> action = new PrivilegedAction<S>() {
public S run() { return nextService(); }
};
return AccessController.doPrivileged(action, acc);
}
}
...
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
// 清空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
}
}

dubbo的spi

一、es入门
集合框架
  1. 1. 目录
  2. 2. 源码
    1. 2.1. lazy迭代器
  3. 3. dubbo的spi
© 2023 haoxp
Hexo theme