com.github.simy4.xpath.util.LazyMemoizedServiceLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of xpath-to-xml-core Show documentation
Show all versions of xpath-to-xml-core Show documentation
Convenient utility to build XML models by evaluating XPath expressions
/*
* Copyright 2019-2021 Alex Simkin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.simy4.xpath.util;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ServiceLoader;
public final class LazyMemoizedServiceLoader implements Function, Iterable> {
private volatile Collection memoized;
@Override
public Iterable apply(Class clazz) {
return memoized == null ? loadAndMemoize(clazz) : memoized;
}
private synchronized Iterable loadAndMemoize(final Class clazz) {
if (memoized == null) {
memoized = AccessController.doPrivileged(new ServiceLoaderAction(clazz));
}
return memoized;
}
private static final class ServiceLoaderAction implements PrivilegedAction> {
private final Class clazz;
private ServiceLoaderAction(Class clazz) {
this.clazz = clazz;
}
@Override
public Collection run() {
final ServiceLoader serviceLoader = ServiceLoader.load(clazz);
final Collection services = new ArrayList();
for (T service : serviceLoader) {
services.add(service);
}
return Collections.unmodifiableCollection(services);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy