Skip to content

SPI 使用优化 #89

@999bug

Description

@999bug

github.javaguide.enums.SerializationTypeEnum#getName(byte) 返回一个默认实现比较好,这样在下面调用github.javaguide.extension.ExtensionLoader#getExtension 就不会返回null,导致程序异常

public static String getName(byte code) {
for (SerializationTypeEnum c : SerializationTypeEnum.values()) {
if (c.getCode() == code) {
return c.name;
}
}
return null;
}

public T getExtension(String name) {
if (StringUtil.isBlank(name)) {
throw new IllegalArgumentException("Extension name should not be null or empty.");
}
// 创建一个对象,如果没有的情况下,创建一个新的
Holder holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<>());
holder = cachedInstances.get(name);
}
// 单例模式创建对象,双检测锁。没有只是使用ConcurrentHashMap
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
instance = holder.get();
if (instance == null) {
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions