repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JavassistParameterNameReader.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/JavassistParameterNameReader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.LoaderClassPath;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.Descriptor;
import javassist.bytecode.LocalVariableAttribute;
import static org.apache.dubbo.common.logger.LoggerFactory.getErrorTypeAwareLogger;
@Activate(order = 100, onClass = "javassist.ClassPool")
public class JavassistParameterNameReader implements ParameterNameReader {
private static final ErrorTypeAwareLogger LOG = getErrorTypeAwareLogger(JavassistParameterNameReader.class);
private final Map<Integer, ClassPool> classPoolMap = CollectionUtils.newConcurrentHashMap();
@Override
public String[] readParameterNames(Method method) {
try {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length == 0) {
return StringUtils.EMPTY_STRING_ARRAY;
}
String descriptor = getDescriptor(paramTypes, method.getReturnType());
Class<?> clazz = method.getDeclaringClass();
CtMethod ctMethod = getClassPool(clazz).get(clazz.getName()).getMethod(method.getName(), descriptor);
return read(ctMethod, Modifier.isStatic(method.getModifiers()) ? 0 : 1, paramTypes.length);
} catch (Throwable t) {
LOG.warn(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Read parameter names error", t);
return null;
}
}
@Override
public String[] readParameterNames(Constructor<?> ctor) {
try {
Class<?>[] paramTypes = ctor.getParameterTypes();
if (paramTypes.length == 0) {
return StringUtils.EMPTY_STRING_ARRAY;
}
String descriptor = getDescriptor(paramTypes, void.class);
Class<?> clazz = ctor.getDeclaringClass();
CtConstructor ctCtor = getClassPool(clazz).get(clazz.getName()).getConstructor(descriptor);
return read(ctCtor, 1, paramTypes.length);
} catch (Throwable t) {
LOG.warn(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Read parameter names error", t);
return null;
}
}
private static String getDescriptor(Class<?>[] parameterTypes, Class<?> returnType) {
StringBuilder descriptor = new StringBuilder(32);
descriptor.append('(');
for (Class<?> type : parameterTypes) {
descriptor.append(toJvmName(type));
}
descriptor.append(')');
descriptor.append(toJvmName(returnType));
return descriptor.toString();
}
private static String toJvmName(Class<?> clazz) {
return clazz.isArray() ? Descriptor.toJvmName(clazz.getName()) : Descriptor.of(clazz.getName());
}
private ClassPool getClassPool(Class<?> clazz) {
ClassLoader classLoader = ClassUtils.getClassLoader(clazz);
return classPoolMap.computeIfAbsent(System.identityHashCode(classLoader), k -> {
ClassPool pool = new ClassPool();
pool.appendClassPath(new LoaderClassPath(classLoader));
return pool;
});
}
private static String[] read(CtBehavior behavior, int start, int len) {
if (behavior == null) {
return null;
}
CodeAttribute codeAttr = behavior.getMethodInfo().getCodeAttribute();
if (codeAttr == null) {
return null;
}
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttr.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
return null;
}
String[] names = new String[len];
for (int i = 0, tLen = attr.tableLength(); i < tLen; i++) {
int j = attr.index(i) - start;
if (j >= 0 && j < len) {
names[j] = attr.variableName(i);
}
}
return names;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.function.Supplier;
public class CacheableSupplier<T> implements Supplier<T> {
private volatile T object;
private final Supplier<T> supplier;
public CacheableSupplier(Supplier<T> supplier) {
this.supplier = supplier;
}
public static <T> CacheableSupplier<T> newSupplier(Supplier<T> supplier) {
return new CacheableSupplier<>(supplier);
}
@Override
public T get() {
if (this.object == null) {
this.object = supplier.get();
}
return object;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import java.lang.annotation.Annotation;
import java.util.List;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute;
import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty;
import static org.apache.dubbo.common.utils.ClassUtils.isGenericClass;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
/**
* The resolver class for {@link Service @Service}
*
* @see Service
* @see com.alibaba.dubbo.config.annotation.Service
* @since 2.7.6
*/
public class ServiceAnnotationResolver {
/**
* The annotation {@link Class classes} of Dubbo Service (read-only)
*
* @since 2.7.9
*/
public static List<Class<? extends Annotation>> SERVICE_ANNOTATION_CLASSES = loadServiceAnnotationClasses();
private static List<Class<? extends Annotation>> loadServiceAnnotationClasses() {
if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) {
return unmodifiableList(asList(DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass()));
} else {
return unmodifiableList(asList(DubboService.class, Service.class));
}
}
private final Annotation serviceAnnotation;
private final Class<?> serviceType;
public ServiceAnnotationResolver(Class<?> serviceType) throws IllegalArgumentException {
this.serviceType = serviceType;
this.serviceAnnotation = getServiceAnnotation(serviceType);
}
private Annotation getServiceAnnotation(Class<?> serviceType) {
Annotation serviceAnnotation = null;
for (Class<? extends Annotation> serviceAnnotationClass : SERVICE_ANNOTATION_CLASSES) {
serviceAnnotation = serviceType.getAnnotation(serviceAnnotationClass);
if (serviceAnnotation != null) {
break;
}
}
if (serviceAnnotation == null) {
throw new IllegalArgumentException(format(
"Any annotation of [%s] can't be annotated in the service type[%s].",
SERVICE_ANNOTATION_CLASSES, serviceType.getName()));
}
return serviceAnnotation;
}
/**
* Resolve the class name of interface
*
* @return if not found, return <code>null</code>
*/
public String resolveInterfaceClassName() {
Class interfaceClass;
// first, try to get the value from "interfaceName" attribute
String interfaceName = resolveAttribute("interfaceName");
if (isEmpty(interfaceName)) { // If not found, try "interfaceClass"
interfaceClass = resolveAttribute("interfaceClass");
} else {
interfaceClass = resolveClass(interfaceName, getClass().getClassLoader());
}
if (isGenericClass(interfaceClass)) {
interfaceName = interfaceClass.getName();
} else {
interfaceName = null;
}
if (isEmpty(interfaceName)) { // If not fund, try to get the first interface from the service type
Class[] interfaces = serviceType.getInterfaces();
if (isNotEmpty(interfaces)) {
interfaceName = interfaces[0].getName();
}
}
return interfaceName;
}
public String resolveVersion() {
return resolveAttribute("version");
}
public String resolveGroup() {
return resolveAttribute("group");
}
private <T> T resolveAttribute(String attributeName) {
return getAttribute(serviceAnnotation, attributeName);
}
public Annotation getServiceAnnotation() {
return serviceAnnotation;
}
public Class<?> getServiceType() {
return serviceType;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.StreamSupport.stream;
import static org.apache.dubbo.common.function.Predicates.and;
import static org.apache.dubbo.common.function.Streams.filterAll;
import static org.apache.dubbo.common.function.Streams.filterList;
import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces;
import static org.apache.dubbo.common.utils.ClassUtils.getAllSuperClasses;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
/**
* The utilities class for {@link Type}
*
* @since 2.7.6
*/
public interface TypeUtils {
Predicate<Class<?>> NON_OBJECT_TYPE_FILTER = t -> !Objects.equals(Object.class, t);
static boolean isParameterizedType(Type type) {
return type instanceof ParameterizedType;
}
static Type getRawType(Type type) {
if (isParameterizedType(type)) {
return ((ParameterizedType) type).getRawType();
} else {
return type;
}
}
static Class<?> getRawClass(Type type) {
Type rawType = getRawType(type);
if (isClass(rawType)) {
return (Class) rawType;
}
return null;
}
static boolean isClass(Type type) {
return type instanceof Class;
}
static <T> Class<T> findActualTypeArgument(Type type, Class<?> interfaceClass, int index) {
return (Class<T>) findActualTypeArguments(type, interfaceClass).get(index);
}
static List<Class<?>> findActualTypeArguments(Type type, Class<?> interfaceClass) {
List<Class<?>> actualTypeArguments = new ArrayList<>();
getAllGenericTypes(type, t -> isAssignableFrom(interfaceClass, getRawClass(t)))
.forEach(parameterizedType -> {
Class<?> rawClass = getRawClass(parameterizedType);
Type[] typeArguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < typeArguments.length; i++) {
Type typeArgument = typeArguments[i];
if (typeArgument instanceof Class) {
actualTypeArguments.add(i, (Class) typeArgument);
}
}
Class<?> superClass = rawClass.getSuperclass();
if (superClass != null) {
actualTypeArguments.addAll(findActualTypeArguments(superClass, interfaceClass));
}
});
return unmodifiableList(actualTypeArguments);
}
/**
* Get the specified types' generic types(including super classes and interfaces) that are assignable from {@link ParameterizedType} interface
*
* @param type the specified type
* @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance
* @return non-null read-only {@link List}
*/
static List<ParameterizedType> getGenericTypes(Type type, Predicate<ParameterizedType>... typeFilters) {
Class<?> rawClass = getRawClass(type);
if (rawClass == null) {
return emptyList();
}
List<Type> genericTypes = new LinkedList<>();
genericTypes.add(rawClass.getGenericSuperclass());
genericTypes.addAll(asList(rawClass.getGenericInterfaces()));
return unmodifiableList(filterList(genericTypes, TypeUtils::isParameterizedType).stream()
.map(ParameterizedType.class::cast)
.filter(and(typeFilters))
.collect(toList()));
}
/**
* Get all generic types(including super classes and interfaces) that are assignable from {@link ParameterizedType} interface
*
* @param type the specified type
* @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance
* @return non-null read-only {@link List}
*/
static List<ParameterizedType> getAllGenericTypes(Type type, Predicate<ParameterizedType>... typeFilters) {
List<ParameterizedType> allGenericTypes = new LinkedList<>();
// Add generic super classes
allGenericTypes.addAll(getAllGenericSuperClasses(type, typeFilters));
// Add generic super interfaces
allGenericTypes.addAll(getAllGenericInterfaces(type, typeFilters));
// wrap unmodifiable object
return unmodifiableList(allGenericTypes);
}
/**
* Get all generic super classes that are assignable from {@link ParameterizedType} interface
*
* @param type the specified type
* @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance
* @return non-null read-only {@link List}
*/
static List<ParameterizedType> getAllGenericSuperClasses(Type type, Predicate<ParameterizedType>... typeFilters) {
Class<?> rawClass = getRawClass(type);
if (rawClass == null || rawClass.isInterface()) {
return emptyList();
}
List<Class<?>> allTypes = new LinkedList<>();
// Add current class
allTypes.add(rawClass);
// Add all super classes
allTypes.addAll(getAllSuperClasses(rawClass, NON_OBJECT_TYPE_FILTER));
List<ParameterizedType> allGenericSuperClasses = allTypes.stream()
.map(Class::getGenericSuperclass)
.filter(TypeUtils::isParameterizedType)
.map(ParameterizedType.class::cast)
.collect(Collectors.toList());
return unmodifiableList(filterAll(allGenericSuperClasses, typeFilters));
}
/**
* Get all generic interfaces that are assignable from {@link ParameterizedType} interface
*
* @param type the specified type
* @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance
* @return non-null read-only {@link List}
*/
static List<ParameterizedType> getAllGenericInterfaces(Type type, Predicate<ParameterizedType>... typeFilters) {
Class<?> rawClass = getRawClass(type);
if (rawClass == null) {
return emptyList();
}
List<Class<?>> allTypes = new LinkedList<>();
// Add current class
allTypes.add(rawClass);
// Add all super classes
allTypes.addAll(getAllSuperClasses(rawClass, NON_OBJECT_TYPE_FILTER));
// Add all super interfaces
allTypes.addAll(getAllInterfaces(rawClass));
List<ParameterizedType> allGenericInterfaces = allTypes.stream()
.map(Class::getGenericInterfaces)
.map(Arrays::asList)
.flatMap(Collection::stream)
.filter(TypeUtils::isParameterizedType)
.map(ParameterizedType.class::cast)
.collect(toList());
return unmodifiableList(filterAll(allGenericInterfaces, typeFilters));
}
static String getClassName(Type type) {
return getRawType(type).getTypeName();
}
static Set<String> getClassNames(Iterable<? extends Type> types) {
return stream(types.spliterator(), false).map(TypeUtils::getClassName).collect(toSet());
}
static Class<?> getSuperGenericType(Class<?> clazz, int index) {
Class<?> result = getArgumentClass(clazz.getGenericSuperclass(), index);
return result == null ? getArgumentClass(ArrayUtils.first(clazz.getGenericInterfaces()), index) : result;
}
static Class<?> getArgumentClass(Type type, int index) {
if (type instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments();
if (index < typeArgs.length) {
Type typeArg = typeArgs[index];
if (typeArg instanceof Class) {
return (Class<?>) typeArg;
} else if (typeArg instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) typeArg).getRawType();
}
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.Method;
/**
* @see org.apache.dubbo.common.utils.ClassUtils
* @deprecated Replace to <code>ClassUtils</code>
*/
public class ClassHelper {
public static Class<?> forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException {
return ClassUtils.forName(name, Thread.currentThread().getContextClassLoader());
}
public static Class<?> forNameWithCallerClassLoader(String name, Class<?> caller) throws ClassNotFoundException {
return ClassUtils.forName(name, caller.getClassLoader());
}
public static ClassLoader getCallerClassLoader(Class<?> caller) {
return caller.getClassLoader();
}
/**
* get class loader
*
* @param clazz
* @return class loader
*/
public static ClassLoader getClassLoader(Class<?> clazz) {
return ClassUtils.getClassLoader(clazz);
}
/**
* Return the default ClassLoader to use: typically the thread context
* ClassLoader, if available; the ClassLoader that loaded the ClassUtils
* class will be used as fallback.
* <p>
* Call this method if you intend to use the thread context ClassLoader in a
* scenario where you absolutely need a non-null ClassLoader reference: for
* example, for class path resource loading (but not necessarily for
* <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader
* reference as well).
*
* @return the default ClassLoader (never <code>null</code>)
* @see java.lang.Thread#getContextClassLoader()
*/
public static ClassLoader getClassLoader() {
return getClassLoader(ClassHelper.class);
}
/**
* Same as <code>Class.forName()</code>, except that it works for primitive
* types.
*/
public static Class<?> forName(String name) throws ClassNotFoundException {
return forName(name, getClassLoader());
}
/**
* Replacement for <code>Class.forName()</code> that also returns Class
* instances for primitives (like "int") and array class names (like
* "String[]").
*
* @param name the name of the Class
* @param classLoader the class loader to use (may be <code>null</code>,
* which indicates the default class loader)
* @return Class instance for the supplied name
* @throws ClassNotFoundException if the class was not found
* @throws LinkageError if the class file could not be loaded
* @see Class#forName(String, boolean, ClassLoader)
*/
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
return ClassUtils.forName(name, classLoader);
}
/**
* Resolve the given class name as primitive class, if appropriate,
* according to the JVM's naming rules for primitive classes.
* <p>
* Also supports the JVM's internal class names for primitive arrays. Does
* <i>not</i> support the "[]" suffix notation for primitive arrays; this is
* only supported by {@link #forName}.
*
* @param name the name of the potentially primitive class
* @return the primitive class, or <code>null</code> if the name does not
* denote a primitive class or primitive array class
*/
public static Class<?> resolvePrimitiveClassName(String name) {
return ClassUtils.resolvePrimitiveClassName(name);
}
public static String toShortString(Object obj) {
return ClassUtils.toShortString(obj);
}
public static String simpleClassName(Class<?> clazz) {
return ClassUtils.simpleClassName(clazz);
}
/**
* @see org.apache.dubbo.common.utils.MethodUtils#isSetter(Method)
* @deprecated Replace to <code>MethodUtils#isSetter(Method)</code>
*/
public static boolean isSetter(Method method) {
return MethodUtils.isSetter(method);
}
/**
* @see org.apache.dubbo.common.utils.MethodUtils#isGetter(Method) (Method)
* @deprecated Replace to <code>MethodUtils#isGetter(Method)</code>
*/
public static boolean isGetter(Method method) {
return MethodUtils.isGetter(method);
}
public static boolean isPrimitive(Class<?> type) {
return ClassUtils.isPrimitive(type);
}
public static Object convertPrimitive(Class<?> type, String value) {
return ClassUtils.convertPrimitive(type, value);
}
/**
* We only check boolean value at this moment.
*
* @param type
* @param value
* @return
*/
public static boolean isTypeMatch(Class<?> type, String value) {
return ClassUtils.isTypeMatch(type, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
public class SerializeSecurityManager {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityManager.class);
private final Set<String> allowedPrefix = new ConcurrentHashSet<>();
private final Set<String> alwaysAllowedPrefix = new ConcurrentHashSet<>();
private final Set<String> disAllowedPrefix = new ConcurrentHashSet<>();
private final Set<AllowClassNotifyListener> listeners = new ConcurrentHashSet<>();
private final Set<String> warnedClasses = new ConcurrentHashSet<>(1);
private volatile SerializeCheckStatus checkStatus = null;
private volatile SerializeCheckStatus defaultCheckStatus = AllowClassNotifyListener.DEFAULT_STATUS;
private volatile Boolean checkSerializable = null;
public void addToAlwaysAllowed(String className) {
boolean modified = alwaysAllowedPrefix.add(className);
if (modified) {
notifyPrefix();
}
}
public void addToAllowed(String className) {
if (disAllowedPrefix.stream().anyMatch(className::startsWith)) {
return;
}
boolean modified = allowedPrefix.add(className);
if (modified) {
notifyPrefix();
}
}
public void addToDisAllowed(String className) {
boolean modified = disAllowedPrefix.add(className);
modified = allowedPrefix.removeIf(allow -> allow.startsWith(className)) || modified;
if (modified) {
notifyPrefix();
}
String lowerCase = className.toLowerCase(Locale.ROOT);
if (!Objects.equals(lowerCase, className)) {
addToDisAllowed(lowerCase);
}
}
public void setCheckStatus(SerializeCheckStatus checkStatus) {
if (this.checkStatus == null) {
this.checkStatus = checkStatus;
logger.info("Serialize check level: " + checkStatus.name());
notifyCheckStatus();
return;
}
// If has been set to WARN, ignore STRICT
if (this.checkStatus.level() <= checkStatus.level()) {
return;
}
this.checkStatus = checkStatus;
logger.info("Serialize check level: " + checkStatus.name());
notifyCheckStatus();
}
public void setDefaultCheckStatus(SerializeCheckStatus checkStatus) {
this.defaultCheckStatus = checkStatus;
logger.info("Serialize check default level: " + checkStatus.name());
notifyCheckStatus();
}
public void setCheckSerializable(boolean checkSerializable) {
if (this.checkSerializable == null || (Boolean.TRUE.equals(this.checkSerializable) && !checkSerializable)) {
this.checkSerializable = checkSerializable;
logger.info("Serialize check serializable: " + checkSerializable);
notifyCheckSerializable();
}
}
public void registerListener(AllowClassNotifyListener listener) {
listeners.add(listener);
listener.notifyPrefix(getAllowedPrefix(), getDisAllowedPrefix());
listener.notifyCheckSerializable(isCheckSerializable());
listener.notifyCheckStatus(getCheckStatus());
}
private void notifyPrefix() {
for (AllowClassNotifyListener listener : listeners) {
listener.notifyPrefix(getAllowedPrefix(), getDisAllowedPrefix());
}
}
private void notifyCheckStatus() {
for (AllowClassNotifyListener listener : listeners) {
listener.notifyCheckStatus(getCheckStatus());
}
}
private void notifyCheckSerializable() {
for (AllowClassNotifyListener listener : listeners) {
listener.notifyCheckSerializable(isCheckSerializable());
}
}
protected SerializeCheckStatus getCheckStatus() {
return checkStatus == null ? defaultCheckStatus : checkStatus;
}
protected Set<String> getAllowedPrefix() {
Set<String> set = new ConcurrentHashSet<>();
set.addAll(allowedPrefix);
set.addAll(alwaysAllowedPrefix);
return set;
}
protected Set<String> getDisAllowedPrefix() {
Set<String> set = new ConcurrentHashSet<>();
set.addAll(disAllowedPrefix);
return set;
}
protected boolean isCheckSerializable() {
return checkSerializable == null || checkSerializable;
}
public Set<String> getWarnedClasses() {
return warnedClasses;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java | dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
/**
* Helper Class for hold a value.
*/
public class Holder<T> {
private volatile T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardOldestPolicy.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardOldestPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import java.util.Queue;
/**
* A handler for rejected element that discards the oldest element.
*/
public class DiscardOldestPolicy<E> implements Rejector<E> {
@Override
public void reject(final E e, final Queue<E> queue) {
queue.poll();
queue.offer(e);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import org.apache.dubbo.common.resource.Disposable;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* <p>
* A safe and lazy and removable initializer implementation that wraps a
* {@code Callable} object.
* </p>
* @see org.apache.commons.lang3.concurrent.AtomicSafeInitializer
*/
public class CallableSafeInitializer<T> {
/** A guard which ensures that initialize() is called only once. */
private final AtomicReference<CallableSafeInitializer<T>> factory = new AtomicReference<>();
/** Holds the reference to the managed object. */
private final AtomicReference<T> reference = new AtomicReference<>();
/** The Callable to be executed. */
private final Callable<T> callable;
public CallableSafeInitializer(Callable<T> callable) {
this.callable = callable;
}
/**
* Get (and initialize, if not initialized yet) the required object
*
* @return lazily initialized object
* exception
*/
// @Override
public final T get() {
T result;
while ((result = reference.get()) == null) {
if (factory.compareAndSet(null, this)) {
reference.set(initialize());
}
}
return result;
}
/**
* Creates and initializes the object managed by this
* {@code AtomicInitializer}. This method is called by {@link #get()} when
* the managed object is not available yet. An implementation can focus on
* the creation of the object. No synchronization is needed, as this is
* already handled by {@code get()}. This method is guaranteed to be called
* only once.
*
* @return the managed data object
*/
protected T initialize() {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public T remove() {
return this.remove(null);
}
public T remove(Consumer<? super T> action) {
// release
T value = reference.getAndSet(null);
if (value != null) {
if (action != null) {
action.accept(value);
}
if (value instanceof Disposable) {
((Disposable) value).destroy();
}
}
factory.set(null);
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue;
/**
* Exception thrown by an {@link MemorySafeLinkedBlockingQueue} when an element cannot be accepted.
*/
public class RejectException extends RuntimeException {
private static final long serialVersionUID = -3240015871717170195L;
/**
* Constructs a {@code RejectException} with no detail message. The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause(Throwable) initCause}.
*/
public RejectException() {}
/**
* Constructs a {@code RejectException} with the specified detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause(Throwable) initCause}.
*
* @param message the detail message
*/
public RejectException(final String message) {
super(message);
}
/**
* Constructs a {@code RejectException} with the specified detail message and cause.
*
* @param message the detail message
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
*/
public RejectException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructs a {@code RejectException} with the specified cause. The detail message is set to {@code (cause == null ? null :
* cause.toString())} (which typically contains the class and detail message of {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
*/
public RejectException(final Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/Rejector.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/Rejector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import java.util.Queue;
/**
* RejectHandler, it works when you need to custom reject action.
*
* @see AbortPolicy
* @see DiscardPolicy
* @see DiscardOldestPolicy
*/
public interface Rejector<E> {
/**
* Method that may be invoked by a Queue when Queue has remained memory
* return true. This may occur when no more memory are available because their bounds would be exceeded.
*
* <p>In the absence of other alternatives, the method may throw an unchecked
* {@link RejectException}, which will be propagated to the caller.
*
* @param e the element requested to be added
* @param queue the queue attempting to add this element
*
* @throws RejectException if there is no more memory
*/
void reject(E e, Queue<E> queue);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import java.util.Queue;
/**
* A handler for rejected element that throws a {@code RejectException}.
*/
public class AbortPolicy<E> implements Rejector<E> {
@Override
public void reject(final E e, final Queue<E> queue) {
throw new RejectException("no more memory can be used !");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java | dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import java.util.Queue;
/**
* A handler for rejected element that silently discards the rejected element.
*/
public class DiscardPolicy<E> implements Rejector<E> {
@Override
public void reject(final E e, final Queue<E> queue) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java | dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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 org.apache.dubbo.common.timer;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Schedules {@link TimerTask}s for one-time future execution in a background
* thread.
*/
public interface Timer {
/**
* Schedules the specified {@link TimerTask} for one-time execution after
* the specified delay.
*
* @return a handle which is associated with the specified task
* @throws IllegalStateException if this timer has been {@linkplain #stop() stopped} already
* @throws RejectedExecutionException if the pending timeouts are too many and creating new timeout
* can cause instability in the system.
*/
Timeout newTimeout(TimerTask task, long delay, TimeUnit unit);
/**
* Releases all resources acquired by this {@link Timer} and cancels all
* tasks which were scheduled but not executed yet.
*
* @return the handles associated with the tasks which were canceled by
* this method
*/
Set<Timeout> stop();
/**
* the timer is stop
*
* @return true for stop
*/
boolean isStop();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timeout.java | dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timeout.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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 org.apache.dubbo.common.timer;
/**
* A handle associated with a {@link TimerTask} that is returned by a
* {@link Timer}.
*/
public interface Timeout {
/**
* Returns the {@link Timer} that created this handle.
*/
Timer timer();
/**
* Returns the {@link TimerTask} which is associated with this handle.
*/
TimerTask task();
/**
* Returns {@code true} if and only if the {@link TimerTask} associated
* with this handle has been expired.
*/
boolean isExpired();
/**
* Returns {@code true} if and only if the {@link TimerTask} associated
* with this handle has been cancelled.
*/
boolean isCancelled();
/**
* Attempts to cancel the {@link TimerTask} associated with this handle.
* If the task has been executed or cancelled already, it will return with
* no side effect.
*
* @return True if the cancellation completed successfully, otherwise false
*/
boolean cancel();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/timer/TimerTask.java | dubbo-common/src/main/java/org/apache/dubbo/common/timer/TimerTask.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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 org.apache.dubbo.common.timer;
import java.util.concurrent.TimeUnit;
/**
* A task which is executed after the delay specified with
* {@link Timer#newTimeout(TimerTask, long, TimeUnit)} (TimerTask, long, TimeUnit)}.
*/
public interface TimerTask {
/**
* Executed after the delay specified with
* {@link Timer#newTimeout(TimerTask, long, TimeUnit)}.
*
* @param timeout a handle which is associated with this task
*/
void run(Timeout timeout) throws Exception;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java | dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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 org.apache.dubbo.common.timer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_OS_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_TOO_MANY_INSTANCES;
/**
* A {@link Timer} optimized for approximated I/O timeout scheduling.
*
* <h3>Tick Duration</h3>
* <p>
* As described with 'approximated', this timer does not execute the scheduled
* {@link TimerTask} on time. {@link HashedWheelTimer}, on every tick, will
* check if there are any {@link TimerTask}s behind the schedule and execute
* them.
* <p>
* You can increase or decrease the accuracy of the execution timing by
* specifying smaller or larger tick duration in the constructor. In most
* network applications, I/O timeout does not need to be accurate. Therefore,
* the default tick duration is 100 milliseconds, and you will not need to try
* different configurations in most cases.
*
* <h3>Ticks per Wheel (Wheel Size)</h3>
* <p>
* {@link HashedWheelTimer} maintains a data structure called 'wheel'.
* To put simply, a wheel is a hash table of {@link TimerTask}s whose hash
* function is 'deadline of the task'. The default number of ticks per wheel
* (i.e. the size of the wheel) is 512. You could specify a larger value
* if you are going to schedule a lot of timeouts.
*
* <h3>Do not create many instances.</h3>
* <p>
* {@link HashedWheelTimer} creates a new thread whenever it is instantiated and
* started. Therefore, you should make sure to create only one instance and
* share it across your application. One of the common mistakes, that makes
* your application unresponsive, is to create a new instance for every connection.
*
* <h3>Implementation Details</h3>
* <p>
* {@link HashedWheelTimer} is based on
* <a href="http://cseweb.ucsd.edu/users/varghese/">George Varghese</a> and
* Tony Lauck's paper,
* <a href="http://cseweb.ucsd.edu/users/varghese/PAPERS/twheel.ps.Z">'Hashed
* and Hierarchical Timing Wheels: data structures to efficiently implement a
* timer facility'</a>. More comprehensive slides are located
* <a href="http://www.cse.wustl.edu/~cdgill/courses/cs6874/TimingWheels.ppt">here</a>.
*/
public class HashedWheelTimer implements Timer {
/**
* may be in spi?
*/
public static final String NAME = "hashed";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HashedWheelTimer.class);
private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger();
private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean();
private static final int INSTANCE_COUNT_LIMIT = 64;
private static final AtomicIntegerFieldUpdater<HashedWheelTimer> WORKER_STATE_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState");
private final Worker worker = new Worker();
private final Thread workerThread;
private static final int WORKER_STATE_INIT = 0;
private static final int WORKER_STATE_STARTED = 1;
private static final int WORKER_STATE_SHUTDOWN = 2;
/**
* 0 - init, 1 - started, 2 - shut down
*/
@SuppressWarnings({"unused", "FieldMayBeFinal"})
private volatile int workerState;
private final long tickDuration;
private final HashedWheelBucket[] wheel;
private final int mask;
private final CountDownLatch startTimeInitialized = new CountDownLatch(1);
private final Queue<HashedWheelTimeout> timeouts = new LinkedBlockingQueue<>();
private final Queue<HashedWheelTimeout> cancelledTimeouts = new LinkedBlockingQueue<>();
private final AtomicLong pendingTimeouts = new AtomicLong(0);
private final long maxPendingTimeouts;
private volatile long startTime;
/**
* Creates a new timer with the default thread factory
* ({@link Executors#defaultThreadFactory()}), default tick duration, and
* default number of ticks per wheel.
*/
public HashedWheelTimer() {
this(Executors.defaultThreadFactory());
}
/**
* Creates a new timer with the default thread factory
* ({@link Executors#defaultThreadFactory()}) and default number of ticks
* per wheel.
*
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @throws NullPointerException if {@code unit} is {@code null}
* @throws IllegalArgumentException if {@code tickDuration} is <= 0
*/
public HashedWheelTimer(long tickDuration, TimeUnit unit) {
this(Executors.defaultThreadFactory(), tickDuration, unit);
}
/**
* Creates a new timer with the default thread factory
* ({@link Executors#defaultThreadFactory()}).
*
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @param ticksPerWheel the size of the wheel
* @throws NullPointerException if {@code unit} is {@code null}
* @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0
*/
public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) {
this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel);
}
/**
* Creates a new timer with the default tick duration and default number of
* ticks per wheel.
*
* @param threadFactory a {@link ThreadFactory} that creates a
* background {@link Thread} which is dedicated to
* {@link TimerTask} execution.
* @throws NullPointerException if {@code threadFactory} is {@code null}
*/
public HashedWheelTimer(ThreadFactory threadFactory) {
this(threadFactory, 100, TimeUnit.MILLISECONDS);
}
/**
* Creates a new timer with the default number of ticks per wheel.
*
* @param threadFactory a {@link ThreadFactory} that creates a
* background {@link Thread} which is dedicated to
* {@link TimerTask} execution.
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null}
* @throws IllegalArgumentException if {@code tickDuration} is <= 0
*/
public HashedWheelTimer(
ThreadFactory threadFactory, long tickDuration, TimeUnit unit) {
this(threadFactory, tickDuration, unit, 512);
}
/**
* Creates a new timer.
*
* @param threadFactory a {@link ThreadFactory} that creates a
* background {@link Thread} which is dedicated to
* {@link TimerTask} execution.
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @param ticksPerWheel the size of the wheel
* @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null}
* @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0
*/
public HashedWheelTimer(
ThreadFactory threadFactory,
long tickDuration, TimeUnit unit, int ticksPerWheel) {
this(threadFactory, tickDuration, unit, ticksPerWheel, -1);
}
/**
* Creates a new timer.
*
* @param threadFactory a {@link ThreadFactory} that creates a
* background {@link Thread} which is dedicated to
* {@link TimerTask} execution.
* @param tickDuration the duration between tick
* @param unit the time unit of the {@code tickDuration}
* @param ticksPerWheel the size of the wheel
* @param maxPendingTimeouts The maximum number of pending timeouts after which call to
* {@code newTimeout} will result in
* {@link java.util.concurrent.RejectedExecutionException}
* being thrown. No maximum pending timeouts limit is assumed if
* this value is 0 or negative.
* @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null}
* @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is <= 0
*/
public HashedWheelTimer(
ThreadFactory threadFactory,
long tickDuration, TimeUnit unit, int ticksPerWheel,
long maxPendingTimeouts) {
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
}
if (unit == null) {
throw new NullPointerException("unit");
}
if (tickDuration <= 0) {
throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
}
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
// Normalize ticksPerWheel to power of two and initialize the wheel.
wheel = createWheel(ticksPerWheel);
mask = wheel.length - 1;
// Convert tickDuration to nanos.
this.tickDuration = unit.toNanos(tickDuration);
// Prevent overflow.
if (this.tickDuration >= Long.MAX_VALUE / wheel.length) {
throw new IllegalArgumentException(String.format(
"tickDuration: %d (expected: 0 < tickDuration in nanos < %d",
tickDuration, Long.MAX_VALUE / wheel.length));
}
workerThread = threadFactory.newThread(worker);
this.maxPendingTimeouts = maxPendingTimeouts;
if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT &&
WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) {
reportTooManyInstances();
}
}
@Override
protected void finalize() throws Throwable {
try {
super.finalize();
} finally {
// This object is going to be GCed and it is assumed the ship has sailed to do a proper shutdown. If
// we have not yet shutdown then we want to make sure we decrement the active instance count.
if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
INSTANCE_COUNTER.decrementAndGet();
}
}
}
private static HashedWheelBucket[] createWheel(int ticksPerWheel) {
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException(
"ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
if (ticksPerWheel > 1073741824) {
throw new IllegalArgumentException(
"ticksPerWheel may not be greater than 2^30: " + ticksPerWheel);
}
ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel);
HashedWheelBucket[] wheel = new HashedWheelBucket[ticksPerWheel];
for (int i = 0; i < wheel.length; i++) {
wheel[i] = new HashedWheelBucket();
}
return wheel;
}
private static int normalizeTicksPerWheel(int ticksPerWheel) {
int normalizedTicksPerWheel = ticksPerWheel - 1;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 1;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 2;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 4;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 8;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 16;
return normalizedTicksPerWheel + 1;
}
/**
* Starts the background thread explicitly. The background thread will
* start automatically on demand even if you did not call this method.
*
* @throws IllegalStateException if this timer has been
* {@linkplain #stop() stopped} already
*/
public void start() {
switch (WORKER_STATE_UPDATER.get(this)) {
case WORKER_STATE_INIT:
if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) {
workerThread.start();
}
break;
case WORKER_STATE_STARTED:
break;
case WORKER_STATE_SHUTDOWN:
throw new IllegalStateException("cannot be started once stopped");
default:
throw new Error("Invalid WorkerState");
}
// Wait until the startTime is initialized by the worker.
while (startTime == 0) {
try {
startTimeInitialized.await();
} catch (InterruptedException ignore) {
// Ignore - it will be ready very soon.
}
}
}
@Override
public Set<Timeout> stop() {
if (Thread.currentThread() == workerThread) {
throw new IllegalStateException(
HashedWheelTimer.class.getSimpleName() +
".stop() cannot be called from " +
TimerTask.class.getSimpleName());
}
if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) {
// workerState can be 0 or 2 at this moment - let it always be 2.
if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
INSTANCE_COUNTER.decrementAndGet();
}
return Collections.emptySet();
}
try {
boolean interrupted = false;
while (workerThread.isAlive()) {
workerThread.interrupt();
try {
workerThread.join(100);
} catch (InterruptedException ignored) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
} finally {
INSTANCE_COUNTER.decrementAndGet();
}
return worker.unprocessedTimeouts();
}
@Override
public boolean isStop() {
return WORKER_STATE_SHUTDOWN == WORKER_STATE_UPDATER.get(this);
}
@Override
public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
if (task == null) {
throw new NullPointerException("task");
}
if (unit == null) {
throw new NullPointerException("unit");
}
long pendingTimeoutsCount = pendingTimeouts.incrementAndGet();
if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) {
pendingTimeouts.decrementAndGet();
throw new RejectedExecutionException("Number of pending timeouts ("
+ pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending "
+ "timeouts (" + maxPendingTimeouts + ")");
}
start();
// Add the timeout to the timeout queue which will be processed on the next tick.
// During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket.
long deadline = System.nanoTime() + unit.toNanos(delay) - startTime;
// Guard against overflow.
if (delay > 0 && deadline < 0) {
deadline = Long.MAX_VALUE;
}
HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline);
timeouts.add(timeout);
return timeout;
}
/**
* Returns the number of pending timeouts of this {@link Timer}.
*/
public long pendingTimeouts() {
return pendingTimeouts.get();
}
private static void reportTooManyInstances() {
String resourceType = ClassUtils.simpleClassName(HashedWheelTimer.class);
logger.error(COMMON_ERROR_TOO_MANY_INSTANCES, "", "", "You are creating too many " + resourceType + " instances. " +
resourceType + " is a shared resource that must be reused across the JVM, " +
"so that only a few instances are created.");
}
private final class Worker implements Runnable {
private final Set<Timeout> unprocessedTimeouts = new HashSet<>();
private long tick;
@Override
public void run() {
// Initialize the startTime.
startTime = System.nanoTime();
if (startTime == 0) {
// We use 0 as an indicator for the uninitialized value here, so make sure it's not 0 when initialized.
startTime = 1;
}
// Notify the other threads waiting for the initialization at start().
startTimeInitialized.countDown();
do {
final long deadline = waitForNextTick();
if (deadline > 0) {
int idx = (int) (tick & mask);
processCancelledTasks();
HashedWheelBucket bucket =
wheel[idx];
transferTimeoutsToBuckets();
bucket.expireTimeouts(deadline);
tick++;
}
} while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED);
// Fill the unprocessedTimeouts so we can return them from stop() method.
for (HashedWheelBucket bucket : wheel) {
bucket.clearTimeouts(unprocessedTimeouts);
}
for (; ; ) {
HashedWheelTimeout timeout = timeouts.poll();
if (timeout == null) {
break;
}
if (!timeout.isCancelled()) {
unprocessedTimeouts.add(timeout);
}
}
processCancelledTasks();
}
private void transferTimeoutsToBuckets() {
// transfer only max. 100000 timeouts per tick to prevent a thread to stale the workerThread when it just
// adds new timeouts in a loop.
for (int i = 0; i < 100000; i++) {
HashedWheelTimeout timeout = timeouts.poll();
if (timeout == null) {
// all processed
break;
}
if (timeout.state() == HashedWheelTimeout.ST_CANCELLED) {
// Was cancelled in the meantime.
continue;
}
long calculated = timeout.deadline / tickDuration;
timeout.remainingRounds = (calculated - tick) / wheel.length;
// Ensure we don't schedule for past.
final long ticks = Math.max(calculated, tick);
int stopIndex = (int) (ticks & mask);
HashedWheelBucket bucket = wheel[stopIndex];
bucket.addTimeout(timeout);
}
}
private void processCancelledTasks() {
for (; ; ) {
HashedWheelTimeout timeout = cancelledTimeouts.poll();
if (timeout == null) {
// all processed
break;
}
try {
timeout.remove();
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown while process a cancellation task", t);
}
}
}
}
/**
* calculate goal nanoTime from startTime and current tick number,
* then wait until that goal has been reached.
*
* @return Long.MIN_VALUE if received a shutdown request,
* current time otherwise (with Long.MIN_VALUE changed by +1)
*/
private long waitForNextTick() {
long deadline = tickDuration * (tick + 1);
for (; ; ) {
final long currentTime = System.nanoTime() - startTime;
long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;
if (sleepTimeMs <= 0) {
if (currentTime == Long.MIN_VALUE) {
return -Long.MAX_VALUE;
} else {
return currentTime;
}
}
if (isWindows()) {
sleepTimeMs = sleepTimeMs / 10 * 10;
}
try {
Thread.sleep(sleepTimeMs);
} catch (InterruptedException ignored) {
if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
return Long.MIN_VALUE;
}
}
}
}
Set<Timeout> unprocessedTimeouts() {
return Collections.unmodifiableSet(unprocessedTimeouts);
}
}
private static final class HashedWheelTimeout implements Timeout {
private static final int ST_INIT = 0;
private static final int ST_CANCELLED = 1;
private static final int ST_EXPIRED = 2;
private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state");
private final HashedWheelTimer timer;
private final TimerTask task;
private final long deadline;
@SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization"})
private volatile int state = ST_INIT;
/**
* RemainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the
* HashedWheelTimeout will be added to the correct HashedWheelBucket.
*/
long remainingRounds;
/**
* This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list.
* As only the workerThread will act on it there is no need for synchronization / volatile.
*/
HashedWheelTimeout next;
HashedWheelTimeout prev;
/**
* The bucket to which the timeout was added
*/
HashedWheelBucket bucket;
HashedWheelTimeout(HashedWheelTimer timer, TimerTask task, long deadline) {
this.timer = timer;
this.task = task;
this.deadline = deadline;
}
@Override
public Timer timer() {
return timer;
}
@Override
public TimerTask task() {
return task;
}
@Override
public boolean cancel() {
// only update the state it will be removed from HashedWheelBucket on next tick.
if (!compareAndSetState(ST_INIT, ST_CANCELLED)) {
return false;
}
// If a task should be canceled we put this to another queue which will be processed on each tick.
// So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way we
// can make again use of our LinkedBlockingQueue and so minimize the locking / overhead as much as possible.
timer.cancelledTimeouts.add(this);
return true;
}
void remove() {
HashedWheelBucket bucket = this.bucket;
if (bucket != null) {
bucket.remove(this);
} else {
timer.pendingTimeouts.decrementAndGet();
}
}
public boolean compareAndSetState(int expected, int state) {
return STATE_UPDATER.compareAndSet(this, expected, state);
}
public int state() {
return state;
}
@Override
public boolean isCancelled() {
return state() == ST_CANCELLED;
}
@Override
public boolean isExpired() {
return state() == ST_EXPIRED;
}
public void expire() {
if (!compareAndSetState(ST_INIT, ST_EXPIRED)) {
return;
}
try {
task.run(this);
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t);
}
}
}
@Override
public String toString() {
final long currentTime = System.nanoTime();
long remaining = deadline - currentTime + timer.startTime;
String simpleClassName = ClassUtils.simpleClassName(this.getClass());
StringBuilder buf = new StringBuilder(192)
.append(simpleClassName)
.append('(')
.append("deadline: ");
if (remaining > 0) {
buf.append(remaining)
.append(" ns later");
} else if (remaining < 0) {
buf.append(-remaining)
.append(" ns ago");
} else {
buf.append("now");
}
if (isCancelled()) {
buf.append(", cancelled");
}
return buf.append(", task: ")
.append(task())
.append(')')
.toString();
}
}
/**
* Bucket that stores HashedWheelTimeouts. These are stored in a linked-list like datastructure to allow easy
* removal of HashedWheelTimeouts in the middle. Also the HashedWheelTimeout act as nodes themself and so no
* extra object creation is needed.
*/
private static final class HashedWheelBucket {
/**
* Used for the linked-list data structure
*/
private HashedWheelTimeout head;
private HashedWheelTimeout tail;
/**
* Add {@link HashedWheelTimeout} to this bucket.
*/
void addTimeout(HashedWheelTimeout timeout) {
assert timeout.bucket == null;
timeout.bucket = this;
if (head == null) {
head = tail = timeout;
} else {
tail.next = timeout;
timeout.prev = tail;
tail = timeout;
}
}
/**
* Expire all {@link HashedWheelTimeout}s for the given {@code deadline}.
*/
void expireTimeouts(long deadline) {
HashedWheelTimeout timeout = head;
// process all timeouts
while (timeout != null) {
HashedWheelTimeout next = timeout.next;
if (timeout.remainingRounds <= 0) {
next = remove(timeout);
if (timeout.deadline <= deadline) {
timeout.expire();
} else {
// The timeout was placed into a wrong slot. This should never happen.
throw new IllegalStateException(String.format(
"timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline));
}
} else if (timeout.isCancelled()) {
next = remove(timeout);
} else {
timeout.remainingRounds--;
}
timeout = next;
}
}
public HashedWheelTimeout remove(HashedWheelTimeout timeout) {
HashedWheelTimeout next = timeout.next;
// remove timeout that was either processed or cancelled by updating the linked-list
if (timeout.prev != null) {
timeout.prev.next = next;
}
if (timeout.next != null) {
timeout.next.prev = timeout.prev;
}
if (timeout == head) {
// if timeout is also the tail we need to adjust the entry too
if (timeout == tail) {
tail = null;
head = null;
} else {
head = next;
}
} else if (timeout == tail) {
// if the timeout is the tail modify the tail to be the prev node.
tail = timeout.prev;
}
// null out prev, next and bucket to allow for GC.
timeout.prev = null;
timeout.next = null;
timeout.bucket = null;
timeout.timer.pendingTimeouts.decrementAndGet();
return next;
}
/**
* Clear this bucket and return all not expired / cancelled {@link Timeout}s.
*/
void clearTimeouts(Set<Timeout> set) {
for (; ; ) {
HashedWheelTimeout timeout = pollTimeout();
if (timeout == null) {
return;
}
if (timeout.isExpired() || timeout.isCancelled()) {
continue;
}
set.add(timeout);
}
}
private HashedWheelTimeout pollTimeout() {
HashedWheelTimeout head = this.head;
if (head == null) {
return null;
}
HashedWheelTimeout next = head.next;
if (next == null) {
tail = this.head = null;
} else {
this.head = next;
next.prev = null;
}
// null out prev and next to allow for GC.
head.next = null;
head.prev = null;
head.bucket = null;
return head;
}
}
private static final boolean IS_OS_WINDOWS = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_OS_NAME, "").toLowerCase(Locale.US).contains(OS_WIN_PREFIX);
private boolean isWindows() {
return IS_OS_WINDOWS;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java | dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.reference;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT;
/**
* inspired by Netty
*/
public abstract class ReferenceCountedResource implements AutoCloseable {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedResource.class);
private static final AtomicLongFieldUpdater<ReferenceCountedResource> COUNTER_UPDATER =
AtomicLongFieldUpdater.newUpdater(ReferenceCountedResource.class, "counter");
private volatile long counter = 1;
/**
* Increments the reference count by 1.
*/
public final ReferenceCountedResource retain() {
long oldCount = COUNTER_UPDATER.getAndIncrement(this);
if (oldCount <= 0) {
COUNTER_UPDATER.getAndDecrement(this);
throw new AssertionError("This instance has been destroyed");
}
return this;
}
/**
* Decreases the reference count by 1 and calls {@link this#destroy} if the reference count reaches 0.
*/
public final boolean release() {
long remainingCount = COUNTER_UPDATER.decrementAndGet(this);
if (remainingCount == 0) {
destroy();
return true;
} else if (remainingCount <= -1) {
logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "This instance has been destroyed");
return false;
} else {
return false;
}
}
/**
* Useful when used together with try-with-resources pattern
*/
@Override
public final void close() {
release();
}
/**
* This method will be invoked when counter reaches 0, override this method to destroy materials related to the specific resource.
*/
protected abstract void destroy();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java | dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.aot;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.GRAALVM_NATIVEIMAGE_IMAGECODE;
public abstract class NativeDetector {
/**
* See https://github.com/oracle/graal/blob/master/sdk/src/org.graalvm.nativeimage/src/org/graalvm/nativeimage/ImageInfo.java
*/
private static final boolean IMAGE_CODE =
(SystemPropertyConfigUtils.getSystemProperty(GRAALVM_NATIVEIMAGE_IMAGECODE) != null);
/**
* Returns {@code true} if invoked in the context of image building or during image runtime, else {@code false}.
*/
public static boolean inNativeImage() {
return IMAGE_CODE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.compact;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import java.lang.annotation.Annotation;
public class Dubbo2CompactUtils {
private static volatile boolean enabled = true;
private static final Class<? extends Annotation> REFERENCE_CLASS;
private static final Class<? extends Annotation> SERVICE_CLASS;
private static final Class<?> ECHO_SERVICE_CLASS;
private static final Class<?> GENERIC_SERVICE_CLASS;
static {
initEnabled();
REFERENCE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Reference");
SERVICE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Service");
ECHO_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.EchoService");
GENERIC_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.GenericService");
}
private static void initEnabled() {
try {
String fromProp =
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO2_COMPACT_ENABLE);
if (StringUtils.isNotEmpty(fromProp)) {
enabled = Boolean.parseBoolean(fromProp);
return;
}
String fromEnv = System.getenv(CommonConstants.DubboProperty.DUBBO2_COMPACT_ENABLE);
if (StringUtils.isNotEmpty(fromEnv)) {
enabled = Boolean.parseBoolean(fromEnv);
return;
}
fromEnv = System.getenv(StringUtils.toOSStyleKey(CommonConstants.DubboProperty.DUBBO2_COMPACT_ENABLE));
enabled = !StringUtils.isNotEmpty(fromEnv) || Boolean.parseBoolean(fromEnv);
} catch (Throwable t) {
enabled = true;
}
}
public static boolean isEnabled() {
return enabled;
}
public static void setEnabled(boolean enabled) {
Dubbo2CompactUtils.enabled = enabled;
}
private static Class<?> loadClass(String name) {
try {
return Class.forName(name);
} catch (Throwable e) {
return null;
}
}
@SuppressWarnings("unchecked")
private static Class<? extends Annotation> loadAnnotation(String name) {
try {
Class<?> clazz = Class.forName(name);
if (clazz.isAnnotation()) {
return (Class<? extends Annotation>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static boolean isReferenceClassLoaded() {
return REFERENCE_CLASS != null;
}
public static Class<? extends Annotation> getReferenceClass() {
return REFERENCE_CLASS;
}
public static boolean isServiceClassLoaded() {
return SERVICE_CLASS != null;
}
public static Class<? extends Annotation> getServiceClass() {
return SERVICE_CLASS;
}
public static boolean isEchoServiceClassLoaded() {
return ECHO_SERVICE_CLASS != null;
}
public static Class<?> getEchoServiceClass() {
return ECHO_SERVICE_CLASS;
}
public static boolean isGenericServiceClassLoaded() {
return GENERIC_SERVICE_CLASS != null;
}
public static Class<?> getGenericServiceClass() {
return GENERIC_SERVICE_CLASS;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.compact;
import org.apache.dubbo.rpc.service.GenericException;
import java.lang.reflect.Constructor;
public class Dubbo2GenericExceptionUtils {
private static final Class<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CLASS;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException>
GENERIC_EXCEPTION_CONSTRUCTOR;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException>
GENERIC_EXCEPTION_CONSTRUCTOR_S;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException>
GENERIC_EXCEPTION_CONSTRUCTOR_S_S;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException>
GENERIC_EXCEPTION_CONSTRUCTOR_T;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException>
GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S;
static {
GENERIC_EXCEPTION_CLASS = loadClass();
GENERIC_EXCEPTION_CONSTRUCTOR = loadConstructor();
GENERIC_EXCEPTION_CONSTRUCTOR_S = loadConstructor(String.class);
GENERIC_EXCEPTION_CONSTRUCTOR_S_S = loadConstructor(String.class, String.class);
GENERIC_EXCEPTION_CONSTRUCTOR_T = loadConstructor(Throwable.class);
GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S =
loadConstructor(String.class, Throwable.class, String.class, String.class);
}
@SuppressWarnings("unchecked")
private static Class<? extends org.apache.dubbo.rpc.service.GenericException> loadClass() {
try {
Class<?> clazz = Class.forName("com.alibaba.dubbo.rpc.service.GenericException");
if (GenericException.class.isAssignableFrom(clazz)) {
return (Class<? extends org.apache.dubbo.rpc.service.GenericException>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
private static Constructor<? extends org.apache.dubbo.rpc.service.GenericException> loadConstructor(
Class<?>... parameterTypes) {
if (GENERIC_EXCEPTION_CLASS == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CLASS.getConstructor(parameterTypes);
} catch (Throwable e) {
return null;
}
}
public static boolean isGenericExceptionClassLoaded() {
return GENERIC_EXCEPTION_CLASS != null
&& GENERIC_EXCEPTION_CONSTRUCTOR != null
&& GENERIC_EXCEPTION_CONSTRUCTOR_S != null
&& GENERIC_EXCEPTION_CONSTRUCTOR_S_S != null
&& GENERIC_EXCEPTION_CONSTRUCTOR_T != null
&& GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S != null;
}
public static Class<? extends org.apache.dubbo.rpc.service.GenericException> getGenericExceptionClass() {
return GENERIC_EXCEPTION_CLASS;
}
public static org.apache.dubbo.rpc.service.GenericException newGenericException() {
if (GENERIC_EXCEPTION_CONSTRUCTOR == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CONSTRUCTOR.newInstance();
} catch (Throwable e) {
return null;
}
}
public static org.apache.dubbo.rpc.service.GenericException newGenericException(String exceptionMessage) {
if (GENERIC_EXCEPTION_CONSTRUCTOR_S == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CONSTRUCTOR_S.newInstance(exceptionMessage);
} catch (Throwable e) {
return null;
}
}
public static org.apache.dubbo.rpc.service.GenericException newGenericException(
String exceptionClass, String exceptionMessage) {
if (GENERIC_EXCEPTION_CONSTRUCTOR_S_S == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CONSTRUCTOR_S_S.newInstance(exceptionClass, exceptionMessage);
} catch (Throwable e) {
return null;
}
}
public static org.apache.dubbo.rpc.service.GenericException newGenericException(Throwable cause) {
if (GENERIC_EXCEPTION_CONSTRUCTOR_T == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CONSTRUCTOR_T.newInstance(cause);
} catch (Throwable e) {
return null;
}
}
public static org.apache.dubbo.rpc.service.GenericException newGenericException(
String message, Throwable cause, String exceptionClass, String exceptionMessage) {
if (GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S == null) {
return null;
}
try {
return GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S.newInstance(message, cause, exceptionClass, exceptionMessage);
} catch (Throwable e) {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.compact;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Dubbo2ActivateUtils {
private static final Class<? extends Annotation> ACTIVATE_CLASS;
private static final Method GROUP_METHOD;
private static final Method VALUE_METHOD;
private static final Method BEFORE_METHOD;
private static final Method AFTER_METHOD;
private static final Method ORDER_METHOD;
private static final Method ON_CLASS_METHOD;
static {
ACTIVATE_CLASS = loadClass();
GROUP_METHOD = loadMethod("group");
VALUE_METHOD = loadMethod("value");
BEFORE_METHOD = loadMethod("before");
AFTER_METHOD = loadMethod("after");
ORDER_METHOD = loadMethod("order");
ON_CLASS_METHOD = loadMethod("onClass");
}
@SuppressWarnings("unchecked")
private static Class<? extends Annotation> loadClass() {
try {
Class<?> clazz = Class.forName("com.alibaba.dubbo.common.extension.Activate");
if (clazz.isAnnotation()) {
return (Class<? extends Annotation>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static boolean isActivateLoaded() {
return ACTIVATE_CLASS != null;
}
public static Class<? extends Annotation> getActivateClass() {
return ACTIVATE_CLASS;
}
private static Method loadMethod(String name) {
if (ACTIVATE_CLASS == null) {
return null;
}
try {
return ACTIVATE_CLASS.getMethod(name);
} catch (Throwable e) {
return null;
}
}
public static String[] getGroup(Annotation annotation) {
if (GROUP_METHOD == null) {
return null;
}
try {
Object result = GROUP_METHOD.invoke(annotation);
if (result instanceof String[]) {
return (String[]) result;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static String[] getValue(Annotation annotation) {
if (VALUE_METHOD == null) {
return null;
}
try {
Object result = VALUE_METHOD.invoke(annotation);
if (result instanceof String[]) {
return (String[]) result;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static String[] getBefore(Annotation annotation) {
if (BEFORE_METHOD == null) {
return null;
}
try {
Object result = BEFORE_METHOD.invoke(annotation);
if (result instanceof String[]) {
return (String[]) result;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static String[] getAfter(Annotation annotation) {
if (AFTER_METHOD == null) {
return null;
}
try {
Object result = AFTER_METHOD.invoke(annotation);
if (result instanceof String[]) {
return (String[]) result;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static int getOrder(Annotation annotation) {
if (ORDER_METHOD == null) {
return 0;
}
try {
Object result = ORDER_METHOD.invoke(annotation);
if (result instanceof Integer) {
return (Integer) result;
} else {
return 0;
}
} catch (Throwable e) {
return 0;
}
}
public static String[] getOnClass(Annotation annotation) {
if (ON_CLASS_METHOD == null) {
return null;
}
try {
Object result = ON_CLASS_METHOD.invoke(annotation);
if (result instanceof String[]) {
return (String[]) result;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
public class ProviderCert extends Cert {
private final AuthPolicy authPolicy;
public ProviderCert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, AuthPolicy authPolicy) {
super(keyCertChain, privateKey, trustCert);
this.authPolicy = authPolicy;
}
public ProviderCert(
byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password, AuthPolicy authPolicy) {
super(keyCertChain, privateKey, trustCert, password);
this.authPolicy = authPolicy;
}
public AuthPolicy getAuthPolicy() {
return authPolicy;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertProvider.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.net.SocketAddress;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface CertProvider {
boolean isSupport(URL address);
default boolean isSupport(URL address, SocketAddress remoteAddress) {
return isSupport(address);
}
ProviderCert getProviderConnectionConfig(URL localAddress);
default ProviderCert getProviderConnectionConfig(URL localAddress, SocketAddress remoteAddress) {
return getProviderConnectionConfig(localAddress);
}
Cert getConsumerConnectionConfig(URL remoteAddress);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/Cert.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/Cert.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class Cert {
private final byte[] keyCertChain;
private final byte[] privateKey;
private final byte[] trustCert;
private final String password;
public Cert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert) {
this(keyCertChain, privateKey, trustCert, null);
}
public Cert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password) {
this.keyCertChain = keyCertChain;
this.privateKey = privateKey;
this.trustCert = trustCert;
this.password = password;
}
public byte[] getKeyCertChain() {
return keyCertChain;
}
public InputStream getKeyCertChainInputStream() {
return keyCertChain != null ? new ByteArrayInputStream(keyCertChain) : null;
}
public byte[] getPrivateKey() {
return privateKey;
}
public InputStream getPrivateKeyInputStream() {
return privateKey != null ? new ByteArrayInputStream(privateKey) : null;
}
public byte[] getTrustCert() {
return trustCert;
}
public InputStream getTrustCertInputStream() {
return trustCert != null ? new ByteArrayInputStream(trustCert) : null;
}
public String getPassword() {
return password;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/AuthPolicy.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/AuthPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
public enum AuthPolicy {
NONE,
SERVER_AUTH,
CLIENT_AUTH
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.net.SocketAddress;
import java.util.List;
public class CertManager {
private final List<CertProvider> certProviders;
public CertManager(FrameworkModel frameworkModel) {
this.certProviders =
frameworkModel.getExtensionLoader(CertProvider.class).getActivateExtensions();
}
public ProviderCert getProviderConnectionConfig(URL localAddress, SocketAddress remoteAddress) {
for (CertProvider certProvider : certProviders) {
if (certProvider.isSupport(localAddress, remoteAddress)) {
ProviderCert cert = certProvider.getProviderConnectionConfig(localAddress, remoteAddress);
if (cert != null) {
return cert;
}
}
}
return null;
}
public Cert getConsumerConnectionConfig(URL remoteAddress) {
for (CertProvider certProvider : certProviders) {
if (certProvider.isSupport(remoteAddress)) {
Cert cert = certProvider.getConsumerConnectionConfig(remoteAddress);
if (cert != null) {
return cert;
}
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java | dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.ssl.AuthPolicy;
import org.apache.dubbo.common.ssl.Cert;
import org.apache.dubbo.common.ssl.CertProvider;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.common.utils.IOUtils;
import java.io.IOException;
import java.util.Objects;
@Activate(order = Integer.MAX_VALUE - 10000)
public class SSLConfigCertProvider implements CertProvider {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SSLConfigCertProvider.class);
@Override
public boolean isSupport(URL address) {
return address.getOrDefaultApplicationModel()
.getApplicationConfigManager()
.getSsl()
.isPresent();
}
@Override
public ProviderCert getProviderConnectionConfig(URL localAddress) {
return localAddress
.getOrDefaultApplicationModel()
.getApplicationConfigManager()
.getSsl()
.filter(sslConfig -> Objects.nonNull(sslConfig.getServerKeyCertChainPath()))
.filter(sslConfig -> Objects.nonNull(sslConfig.getServerPrivateKeyPath()))
.map(sslConfig -> {
try {
return new ProviderCert(
IOUtils.toByteArray(sslConfig.getServerKeyCertChainPathStream()),
IOUtils.toByteArray(sslConfig.getServerPrivateKeyPathStream()),
sslConfig.getServerTrustCertCollectionPath() != null
? IOUtils.toByteArray(sslConfig.getServerTrustCertCollectionPathStream())
: null,
sslConfig.getServerKeyPassword(),
AuthPolicy.CLIENT_AUTH);
} catch (IOException e) {
logger.warn(
LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED,
"",
"",
"Failed to load ssl config.",
e);
return null;
}
})
.orElse(null);
}
@Override
public Cert getConsumerConnectionConfig(URL remoteAddress) {
return remoteAddress
.getOrDefaultApplicationModel()
.getApplicationConfigManager()
.getSsl()
.filter(sslConfig -> Objects.nonNull(sslConfig.getClientKeyCertChainPath()))
.filter(sslConfig -> Objects.nonNull(sslConfig.getClientPrivateKeyPath()))
.map(sslConfig -> {
try {
return new Cert(
IOUtils.toByteArray(sslConfig.getClientKeyCertChainPathStream()),
IOUtils.toByteArray(sslConfig.getClientPrivateKeyPathStream()),
sslConfig.getClientTrustCertCollectionPath() != null
? IOUtils.toByteArray(sslConfig.getClientTrustCertCollectionPathStream())
: null,
sslConfig.getClientKeyPassword());
} catch (IOException e) {
logger.warn(
LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED,
"",
"",
"Failed to load ssl config.",
e);
return null;
}
})
.orElse(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationCache.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Properties Cache of Configuration {@link ConfigurationUtils#getCachedDynamicProperty(ScopeModel, String, String)}
*/
public class ConfigurationCache {
private final Map<String, String> cache = new ConcurrentHashMap<>();
/**
* Get Cached Value
*
* @param key key
* @param function function to produce value, should not return `null`
* @return value
*/
public String computeIfAbsent(String key, Function<String, String> function) {
String value = cache.get(key);
// value might be empty here!
// empty value from config center will be cached here
if (value == null) {
// lock free, tolerate repeat apply, will return previous value
cache.putIfAbsent(key, function.apply(key));
value = cache.get(key);
}
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/PropertiesConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/PropertiesConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.Map;
import java.util.Properties;
/**
* Configuration from system properties and dubbo.properties
*/
public class PropertiesConfiguration implements Configuration {
private Properties properties;
private final ScopeModel scopeModel;
public PropertiesConfiguration(ScopeModel scopeModel) {
this.scopeModel = scopeModel;
refresh();
}
public void refresh() {
properties = ConfigUtils.getProperties(scopeModel.getClassLoaders());
}
@Override
public String getProperty(String key) {
return properties.getProperty(key);
}
@Override
public Object getInternalProperty(String key) {
return properties.getProperty(key);
}
public void setProperty(String key, String value) {
properties.setProperty(key, value);
}
public String remove(String key) {
return (String) properties.remove(key);
}
@Deprecated
public void setProperties(Properties properties) {
this.properties = properties;
}
public Map<String, String> getProperties() {
return (Map) properties;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.util.Properties;
/**
*
* The smaller value, the higher priority
*
*/
@SPI(scope = ExtensionScope.MODULE)
public interface OrderedPropertiesProvider {
/**
* order
*
* @return
*/
int priority();
/**
* load the properties
*
* @return
*/
Properties initProperties();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.NoSuchElementException;
import static org.apache.dubbo.common.config.ConfigurationUtils.isEmptyValue;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
/**
* Configuration interface, to fetch the value for the specified key.
*/
public interface Configuration {
ErrorTypeAwareLogger interfaceLevelLogger = LoggerFactory.getErrorTypeAwareLogger(Configuration.class);
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated string.
*/
default String getString(String key) {
return convert(String.class, key, null);
}
/**
* Get a string associated with the given configuration key.
* If the key doesn't map to an existing object, the default value
* is returned.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated string if key is found and has valid
* format, default value otherwise.
*/
default String getString(String key, String defaultValue) {
return convert(String.class, key, defaultValue);
}
default int getInt(String key) {
Integer i = this.getInteger(key, null);
if (i != null) {
return i;
} else {
throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object");
}
}
default int getInt(String key, int defaultValue) {
Integer i = this.getInteger(key, null);
return i == null ? defaultValue : i;
}
default Integer getInteger(String key, Integer defaultValue) {
try {
return convert(Integer.class, key, defaultValue);
} catch (NumberFormatException e) {
// 0-2 Property type mismatch.
interfaceLevelLogger.error(
COMMON_PROPERTY_TYPE_MISMATCH,
"typo in property value",
"This property requires an integer value.",
"Actual Class: " + getClass().getName(),
e);
throw new IllegalStateException('\'' + key + "' doesn't map to a Integer object", e);
}
}
default boolean getBoolean(String key) {
Boolean b = this.getBoolean(key, null);
if (b != null) {
return b;
} else {
throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object");
}
}
default boolean getBoolean(String key, boolean defaultValue) {
return this.getBoolean(key, toBooleanObject(defaultValue));
}
default Boolean getBoolean(String key, Boolean defaultValue) {
try {
return convert(Boolean.class, key, defaultValue);
} catch (Exception e) {
throw new IllegalStateException(
"Try to get " + '\'' + key + "' failed, maybe because this key doesn't map to a Boolean object", e);
}
}
/**
* Gets a property from the configuration. This is the most basic get
* method for retrieving values of properties. In a typical implementation
* of the {@code Configuration} interface the other get methods (that
* return specific data types) will internally make use of this method. On
* this level variable substitution is not yet performed. The returned
* object is an internal representation of the property value for the passed
* in key. It is owned by the {@code Configuration} object. So a caller
* should not modify this object. It cannot be guaranteed that this object
* will stay constant over time (i.e. further update operations on the
* configuration may change its internal state).
*
* @param key property to retrieve
* @return the value to which this configuration maps the specified key, or
* null if the configuration contains no mapping for this key.
*/
default Object getProperty(String key) {
return getProperty(key, null);
}
/**
* Gets a property from the configuration. The default value will return if the configuration doesn't contain
* the mapping for the specified key.
*
* @param key property to retrieve
* @param defaultValue default value
* @return the value to which this configuration maps the specified key, or default value if the configuration
* contains no mapping for this key.
*/
default Object getProperty(String key, Object defaultValue) {
Object value = getInternalProperty(key);
return value != null ? value : defaultValue;
}
Object getInternalProperty(String key);
/**
* Check if the configuration contains the specified key.
*
* @param key the key whose presence in this configuration is to be tested
* @return {@code true} if the configuration contains a value for this
* key, {@code false} otherwise
*/
default boolean containsKey(String key) {
return !isEmptyValue(getProperty(key));
}
default <T> T convert(Class<T> cls, String key, T defaultValue) {
// we only process String properties for now
String value = (String) getProperty(key);
if (value == null) {
return defaultValue;
}
Object obj = value;
if (cls.isInstance(value)) {
return cls.cast(value);
}
if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) {
obj = Boolean.valueOf(value);
} else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) {
if (Integer.class.equals(cls) || Integer.TYPE.equals(cls)) {
obj = Integer.valueOf(value);
} else if (Long.class.equals(cls) || Long.TYPE.equals(cls)) {
obj = Long.valueOf(value);
} else if (Byte.class.equals(cls) || Byte.TYPE.equals(cls)) {
obj = Byte.valueOf(value);
} else if (Short.class.equals(cls) || Short.TYPE.equals(cls)) {
obj = Short.valueOf(value);
} else if (Float.class.equals(cls) || Float.TYPE.equals(cls)) {
obj = Float.valueOf(value);
} else if (Double.class.equals(cls) || Double.TYPE.equals(cls)) {
obj = Double.valueOf(value);
}
} else if (cls.isEnum()) {
obj = Enum.valueOf(cls.asSubclass(Enum.class), value);
}
return cls.cast(obj);
}
static Boolean toBooleanObject(boolean bool) {
return bool ? Boolean.TRUE : Boolean.FALSE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.utils.StringUtils;
public class PrefixedConfiguration implements Configuration {
private final String prefix;
private final Configuration origin;
public PrefixedConfiguration(Configuration origin, String prefix) {
this.origin = origin;
this.prefix = prefix;
}
@Override
public Object getInternalProperty(String key) {
if (StringUtils.isBlank(prefix)) {
return origin.getInternalProperty(key);
}
Object value = origin.getInternalProperty(prefix + "." + key);
if (!ConfigurationUtils.isEmptyValue(value)) {
return value;
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.context.ModuleExt;
import org.apache.dubbo.common.extension.DisableInject;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
public class ModuleEnvironment extends Environment implements ModuleExt {
// delegate
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ModuleEnvironment.class);
public static final String NAME = "moduleEnvironment";
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final ModuleModel moduleModel;
private final Environment applicationDelegate;
private OrderedPropertiesConfiguration orderedPropertiesConfiguration;
private CompositeConfiguration dynamicGlobalConfiguration;
private DynamicConfiguration dynamicConfiguration;
public ModuleEnvironment(ModuleModel moduleModel) {
super(moduleModel);
this.moduleModel = moduleModel;
this.applicationDelegate = moduleModel.getApplicationModel().modelEnvironment();
}
@Override
public void initialize() throws IllegalStateException {
if (initialized.compareAndSet(false, true)) {
this.orderedPropertiesConfiguration = new OrderedPropertiesConfiguration(moduleModel);
}
}
@Override
public Configuration getPrefixedConfiguration(AbstractConfig config, String prefix) {
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(applicationDelegate.getPrefixedConfiguration(config, prefix));
compositeConfiguration.addConfiguration(orderedPropertiesConfiguration);
return new PrefixedConfiguration(compositeConfiguration, prefix);
}
@Override
public CompositeConfiguration getConfiguration() {
if (globalConfiguration == null) {
CompositeConfiguration configuration = new CompositeConfiguration();
configuration.addConfiguration(applicationDelegate.getConfiguration());
configuration.addConfiguration(orderedPropertiesConfiguration);
globalConfiguration = configuration;
}
return globalConfiguration;
}
@Override
public List<Map<String, String>> getConfigurationMaps(AbstractConfig config, String prefix) {
List<Map<String, String>> maps = applicationDelegate.getConfigurationMaps(config, prefix);
maps.add(orderedPropertiesConfiguration.getProperties());
return maps;
}
@Override
public Configuration getDynamicGlobalConfiguration() {
if (dynamicConfiguration == null) {
CompositeConfiguration configuration = new CompositeConfiguration();
configuration.addConfiguration(applicationDelegate.getDynamicGlobalConfiguration());
configuration.addConfiguration(orderedPropertiesConfiguration);
return configuration;
}
if (dynamicGlobalConfiguration == null) {
dynamicGlobalConfiguration = new CompositeConfiguration();
dynamicGlobalConfiguration.addConfiguration(dynamicConfiguration);
dynamicGlobalConfiguration.addConfiguration(getConfiguration());
}
return dynamicGlobalConfiguration;
}
@Override
public Optional<DynamicConfiguration> getDynamicConfiguration() {
if (dynamicConfiguration == null) {
return applicationDelegate.getDynamicConfiguration();
}
return Optional.ofNullable(dynamicConfiguration);
}
@Override
@DisableInject
public void setDynamicConfiguration(DynamicConfiguration dynamicConfiguration) {
this.dynamicConfiguration = dynamicConfiguration;
}
@Override
public void destroy() throws IllegalStateException {
super.destroy();
this.orderedPropertiesConfiguration = null;
}
@Override
@DisableInject
public void setLocalMigrationRule(String localMigrationRule) {
applicationDelegate.setLocalMigrationRule(localMigrationRule);
}
@Override
@DisableInject
public void setExternalConfigMap(Map<String, String> externalConfiguration) {
applicationDelegate.setExternalConfigMap(externalConfiguration);
}
@Override
@DisableInject
public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) {
applicationDelegate.setAppExternalConfigMap(appExternalConfiguration);
}
@Override
@DisableInject
public void setAppConfigMap(Map<String, String> appConfiguration) {
applicationDelegate.setAppConfigMap(appConfiguration);
}
@Override
public Map<String, String> getExternalConfigMap() {
return applicationDelegate.getExternalConfigMap();
}
@Override
public Map<String, String> getAppExternalConfigMap() {
return applicationDelegate.getAppExternalConfigMap();
}
@Override
public Map<String, String> getAppConfigMap() {
return applicationDelegate.getAppConfigMap();
}
@Override
public void updateExternalConfigMap(Map<String, String> externalMap) {
applicationDelegate.updateExternalConfigMap(externalMap);
}
@Override
public void updateAppExternalConfigMap(Map<String, String> externalMap) {
applicationDelegate.updateAppExternalConfigMap(externalMap);
}
@Override
public void updateAppConfigMap(Map<String, String> map) {
applicationDelegate.updateAppConfigMap(map);
}
@Override
public PropertiesConfiguration getPropertiesConfiguration() {
return applicationDelegate.getPropertiesConfiguration();
}
@Override
public SystemConfiguration getSystemConfiguration() {
return applicationDelegate.getSystemConfiguration();
}
@Override
public EnvironmentConfiguration getEnvironmentConfiguration() {
return applicationDelegate.getEnvironmentConfiguration();
}
@Override
public InmemoryConfiguration getExternalConfiguration() {
return applicationDelegate.getExternalConfiguration();
}
@Override
public InmemoryConfiguration getAppExternalConfiguration() {
return applicationDelegate.getAppExternalConfiguration();
}
@Override
public InmemoryConfiguration getAppConfiguration() {
return applicationDelegate.getAppConfiguration();
}
@Override
public String getLocalMigrationRule() {
return applicationDelegate.getLocalMigrationRule();
}
@Override
public synchronized void refreshClassLoaders() {
orderedPropertiesConfiguration.refresh();
applicationDelegate.refreshClassLoaders();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE;
/**
* This is an abstraction specially customized for the sequence Dubbo retrieves properties.
*/
public class CompositeConfiguration implements Configuration {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeConfiguration.class);
/**
* List holding all the configuration
*/
private final List<Configuration> configList = new CopyOnWriteArrayList<>();
// FIXME, consider change configList to SortedMap to replace this boolean status.
private boolean dynamicIncluded;
public CompositeConfiguration() {}
public CompositeConfiguration(Configuration... configurations) {
if (ArrayUtils.isNotEmpty(configurations)) {
Arrays.stream(configurations)
.filter(config -> !configList.contains(config))
.forEach(configList::add);
}
}
// FIXME, consider changing configList to SortedMap to replace this boolean status.
public boolean isDynamicIncluded() {
return dynamicIncluded;
}
public void setDynamicIncluded(boolean dynamicIncluded) {
this.dynamicIncluded = dynamicIncluded;
}
public void addConfiguration(Configuration configuration) {
if (configList.contains(configuration)) {
return;
}
this.configList.add(configuration);
}
public void addConfigurationFirst(Configuration configuration) {
this.addConfiguration(0, configuration);
}
public void addConfiguration(int pos, Configuration configuration) {
this.configList.add(pos, configuration);
}
@Override
public Object getInternalProperty(String key) {
for (Configuration config : configList) {
try {
Object value = config.getProperty(key);
if (!ConfigurationUtils.isEmptyValue(value)) {
return value;
}
} catch (Exception e) {
logger.error(
CONFIG_FAILED_LOAD_ENV_VARIABLE,
"",
"",
"Error when trying to get value for key " + key + " from " + config + ", "
+ "will continue to try the next one.");
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/EnvironmentConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/EnvironmentConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Configuration from system environment
*/
public class EnvironmentConfiguration implements Configuration {
@Override
public Object getInternalProperty(String key) {
if (StringUtils.isEmpty(key)) {
return null;
}
String value = getenv().get(key);
if (value != null) {
return value;
}
for (String candidateKey : generateCandidateEnvironmentKeys(key)) {
value = getenv().get(candidateKey);
if (value != null) {
return value;
}
}
String osStyleKey = StringUtils.toOSStyleKey(key);
value = getenv().get(osStyleKey);
return value;
}
private Set<String> generateCandidateEnvironmentKeys(String originalKey) {
Set<String> candidates = new LinkedHashSet<>();
String dotsToUnderscores =
originalKey.replace(CommonConstants.DOT_SEPARATOR, CommonConstants.UNDERLINE_SEPARATOR);
String normalizedKey = dotsToUnderscores.replace(
CommonConstants.PROPERTIES_CHAR_SEPARATOR, CommonConstants.UNDERLINE_SEPARATOR);
candidates.add(normalizedKey.toUpperCase(Locale.ROOT));
String springLikeNoHyphens = dotsToUnderscores
.replace(CommonConstants.PROPERTIES_CHAR_SEPARATOR, "")
.toUpperCase(Locale.ROOT);
candidates.add(springLikeNoHyphens);
String dotsToUnderscoresUpper = dotsToUnderscores.toUpperCase(Locale.ROOT);
candidates.add(dotsToUnderscoresUpper);
candidates.add(normalizedKey);
return candidates;
}
public Map<String, String> getProperties() {
return getenv();
}
protected Map<String, String> getenv() {
return System.getenv();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/ReferenceCache.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/ReferenceCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.config.ReferenceConfigBase;
import java.util.List;
public interface ReferenceCache {
@SuppressWarnings("unchecked")
default <T> T get(ReferenceConfigBase<T> referenceConfig) {
return get(referenceConfig, true);
}
@SuppressWarnings("unchecked")
<T> T get(ReferenceConfigBase<T> referenceConfig, boolean check);
@SuppressWarnings("unchecked")
<T> T get(String key, Class<T> type);
@SuppressWarnings("unchecked")
<T> T get(String key);
@SuppressWarnings("unchecked")
<T> List<T> getAll(Class<T> type);
@SuppressWarnings("unchecked")
<T> T get(Class<T> type);
@SuppressWarnings("unchecked")
<T> void check(ReferenceConfigBase<T> referenceConfig, long timeout);
void check(String key, Class<?> type, long timeout);
void destroy(String key, Class<?> type);
void destroy(Class<?> type);
<T> void destroy(ReferenceConfigBase<T> referenceConfig);
void destroyAll();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
import org.apache.dubbo.common.extension.ExtensionAccessor;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
/**
* Utilities for manipulating configurations from different sources
*/
public final class ConfigurationUtils {
/**
* Forbids instantiation.
*/
private ConfigurationUtils() {
throw new UnsupportedOperationException("No instance of 'ConfigurationUtils' for you! ");
}
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigurationUtils.class);
private static final Set<String> securityKey;
private static volatile long expectedShutdownTime = Long.MAX_VALUE;
static {
Set<String> keys = new HashSet<>();
keys.add("accesslog");
keys.add("router");
keys.add("rule");
keys.add("runtime");
keys.add("type");
securityKey = Collections.unmodifiableSet(keys);
}
/**
* Used to get properties from the jvm
*
* @return
*/
public static Configuration getSystemConfiguration(ScopeModel scopeModel) {
return getScopeModelOrDefaultApplicationModel(scopeModel)
.modelEnvironment()
.getSystemConfiguration();
}
/**
* Used to get properties from the os environment
*
* @return
*/
public static Configuration getEnvConfiguration(ScopeModel scopeModel) {
return getScopeModelOrDefaultApplicationModel(scopeModel)
.modelEnvironment()
.getEnvironmentConfiguration();
}
/**
* Used to get a composite property value.
* <p>
* Also see {@link Environment#getConfiguration()}
*
* @return
*/
public static Configuration getGlobalConfiguration(ScopeModel scopeModel) {
return getScopeModelOrDefaultApplicationModel(scopeModel)
.modelEnvironment()
.getConfiguration();
}
public static Configuration getDynamicGlobalConfiguration(ScopeModel scopeModel) {
return scopeModel.modelEnvironment().getDynamicGlobalConfiguration();
}
// FIXME
/**
* Server shutdown wait timeout mills
*
* @return
*/
@SuppressWarnings("deprecation")
public static int getServerShutdownTimeout(ScopeModel scopeModel) {
if (expectedShutdownTime < System.currentTimeMillis()) {
return 1;
}
int timeout = DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
Configuration configuration = getGlobalConfiguration(scopeModel);
String value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_KEY));
if (StringUtils.isNotEmpty(value)) {
try {
timeout = Integer.parseInt(value);
} catch (Exception e) {
// ignore
}
} else {
value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_SECONDS_KEY));
if (StringUtils.isNotEmpty(value)) {
try {
timeout = Integer.parseInt(value) * 1000;
} catch (Exception e) {
// ignore
}
}
}
if (expectedShutdownTime - System.currentTimeMillis() < timeout) {
return (int) Math.max(1, expectedShutdownTime - System.currentTimeMillis());
}
return timeout;
}
public static int reCalShutdownTime(int expected) {
// already timeout
if (expectedShutdownTime < System.currentTimeMillis()) {
return 1;
}
if (expectedShutdownTime - System.currentTimeMillis() < expected) {
// the shutdown time rest is less than expected
return (int) Math.max(1, expectedShutdownTime - System.currentTimeMillis());
}
// return the expected
return expected;
}
public static void setExpectedShutdownTime(long expectedShutdownTime) {
ConfigurationUtils.expectedShutdownTime = expectedShutdownTime;
}
public static String getCachedDynamicProperty(ScopeModel realScopeModel, String key, String defaultValue) {
ScopeModel scopeModel = getScopeModelOrDefaultApplicationModel(realScopeModel);
ConfigurationCache configurationCache = scopeModel.getBeanFactory().getBean(ConfigurationCache.class);
String value = configurationCache.computeIfAbsent(
key, _k -> ConfigurationUtils.getDynamicProperty(scopeModel, _k, ""));
return StringUtils.isEmpty(value) ? defaultValue : value;
}
private static ScopeModel getScopeModelOrDefaultApplicationModel(ScopeModel realScopeModel) {
if (realScopeModel == null) {
return ApplicationModel.defaultModel();
}
return realScopeModel;
}
public static String getDynamicProperty(ScopeModel scopeModel, String property) {
return getDynamicProperty(scopeModel, property, null);
}
public static String getDynamicProperty(ScopeModel scopeModel, String property, String defaultValue) {
return StringUtils.trim(getDynamicGlobalConfiguration(scopeModel).getString(property, defaultValue));
}
public static String getProperty(ScopeModel scopeModel, String property) {
return getProperty(scopeModel, property, null);
}
public static String getProperty(ScopeModel scopeModel, String property, String defaultValue) {
return StringUtils.trim(getGlobalConfiguration(scopeModel).getString(property, defaultValue));
}
public static int get(ScopeModel scopeModel, String property, int defaultValue) {
return getGlobalConfiguration(scopeModel).getInt(property, defaultValue);
}
public static Map<String, String> parseProperties(String content) throws IOException {
Map<String, String> map = new HashMap<>();
if (StringUtils.isEmpty(content)) {
logger.info("Config center was specified, but no config item found.");
} else {
Properties properties = new Properties();
properties.load(new StringReader(content));
properties.stringPropertyNames().forEach(k -> {
boolean deny = false;
// check whether property name is safe or not based on the last fragment kebab-case comparison.
String[] fragments = k.split("\\.");
if (securityKey.contains(StringUtils.convertToSplitName(fragments[fragments.length - 1], "-"))) {
deny = true;
logger.warn(
COMMON_PROPERTY_TYPE_MISMATCH,
"security properties are not allowed to be set",
"",
String.format("'%s' is not allowed to be set as it is on the security key list.", k));
}
if (!deny) {
map.put(k, properties.getProperty(k));
}
});
}
return map;
}
public static boolean isEmptyValue(Object value) {
return value == null || value instanceof String && StringUtils.isBlank((String) value);
}
/**
* Search props and extract sub properties.
* <pre>
* # properties
* dubbo.protocol.name=dubbo
* dubbo.protocol.port=1234
*
* # extract protocol props
* Map props = getSubProperties("dubbo.protocol.");
*
* # result
* props: {"name": "dubbo", "port" : "1234"}
*
* </pre>
*
* @param configMaps
* @param prefix
* @param <V>
* @return
*/
public static <V extends Object> Map<String, V> getSubProperties(
Collection<Map<String, V>> configMaps, String prefix) {
Map<String, V> map = new LinkedHashMap<>();
for (Map<String, V> configMap : configMaps) {
getSubProperties(configMap, prefix, map);
}
return map;
}
public static <V extends Object> Map<String, V> getSubProperties(Map<String, V> configMap, String prefix) {
return getSubProperties(configMap, prefix, null);
}
private static <V extends Object> Map<String, V> getSubProperties(
Map<String, V> configMap, String prefix, Map<String, V> resultMap) {
if (!prefix.endsWith(".")) {
prefix += ".";
}
if (null == resultMap) {
resultMap = new LinkedHashMap<>();
}
if (CollectionUtils.isNotEmptyMap(configMap)) {
Map<String, V> copy;
synchronized (configMap) {
copy = new HashMap<>(configMap);
}
for (Map.Entry<String, V> entry : copy.entrySet()) {
String key = entry.getKey();
V val = entry.getValue();
if ((StringUtils.startsWithIgnoreCase(key, prefix)
|| StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix)))
&& key.length() > prefix.length()
&& !ConfigurationUtils.isEmptyValue(val)) {
String k = key.substring(prefix.length());
// convert camelCase/snake_case to kebab-case
String newK = StringUtils.convertToSplitName(k, "-");
resultMap.putIfAbsent(newK, val);
if (!Objects.equals(k, newK)) {
resultMap.putIfAbsent(k, val);
}
}
}
}
return resultMap;
}
public static <V extends Object> boolean hasSubProperties(Collection<Map<String, V>> configMaps, String prefix) {
if (!prefix.endsWith(".")) {
prefix += ".";
}
for (Map<String, V> configMap : configMaps) {
if (hasSubProperties(configMap, prefix)) {
return true;
}
}
return false;
}
public static <V extends Object> boolean hasSubProperties(Map<String, V> configMap, String prefix) {
if (!prefix.endsWith(".")) {
prefix += ".";
}
Map<String, V> copy;
synchronized (configMap) {
copy = new HashMap<>(configMap);
}
for (Map.Entry<String, V> entry : copy.entrySet()) {
String key = entry.getKey();
if ((StringUtils.startsWithIgnoreCase(key, prefix)
|| StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix)))
&& key.length() > prefix.length()
&& !ConfigurationUtils.isEmptyValue(entry.getValue())) {
return true;
}
}
return false;
}
/**
* Search props and extract config ids
* <pre>
* # properties
* dubbo.registries.registry1.address=xxx
* dubbo.registries.registry2.port=xxx
*
* # extract ids
* Set configIds = getSubIds("dubbo.registries.")
*
* # result
* configIds: ["registry1", "registry2"]
* </pre>
*
* @param configMaps
* @param prefix
* @return
*/
public static <V extends Object> Set<String> getSubIds(Collection<Map<String, V>> configMaps, String prefix) {
if (!prefix.endsWith(".")) {
prefix += ".";
}
Set<String> ids = new LinkedHashSet<>();
for (Map<String, V> configMap : configMaps) {
Map<String, V> copy;
synchronized (configMap) {
copy = new HashMap<>(configMap);
}
for (Map.Entry<String, V> entry : copy.entrySet()) {
String key = entry.getKey();
V val = entry.getValue();
if (StringUtils.startsWithIgnoreCase(key, prefix)
&& key.length() > prefix.length()
&& !ConfigurationUtils.isEmptyValue(val)) {
String k = key.substring(prefix.length());
int endIndex = k.indexOf(".");
if (endIndex > 0) {
String id = k.substring(0, endIndex);
ids.add(id);
}
}
}
}
return ids;
}
/**
* Get an instance of {@link DynamicConfigurationFactory} by the specified name. If not found, take the default
* extension of {@link DynamicConfigurationFactory}
*
* @param name the name of extension of {@link DynamicConfigurationFactory}
* @return non-null
* @see 2.7.4
*/
public static DynamicConfigurationFactory getDynamicConfigurationFactory(
ExtensionAccessor extensionAccessor, String name) {
ExtensionLoader<DynamicConfigurationFactory> loader =
extensionAccessor.getExtensionLoader(DynamicConfigurationFactory.class);
return loader.getOrDefaultExtension(name);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getSystemConfiguration(ScopeModel)}
*/
@Deprecated
public static Configuration getSystemConfiguration() {
return ApplicationModel.defaultModel().modelEnvironment().getSystemConfiguration();
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getEnvConfiguration(ScopeModel)}
*/
@Deprecated
public static Configuration getEnvConfiguration() {
return ApplicationModel.defaultModel().modelEnvironment().getEnvironmentConfiguration();
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getGlobalConfiguration(ScopeModel)}
*/
@Deprecated
public static Configuration getGlobalConfiguration() {
return ApplicationModel.defaultModel().modelEnvironment().getConfiguration();
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getDynamicGlobalConfiguration(ScopeModel)}
*/
@Deprecated
public static Configuration getDynamicGlobalConfiguration() {
return ApplicationModel.defaultModel()
.getDefaultModule()
.modelEnvironment()
.getDynamicGlobalConfiguration();
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getCachedDynamicProperty(ScopeModel, String, String)}
*/
@Deprecated
public static String getCachedDynamicProperty(String key, String defaultValue) {
return getCachedDynamicProperty(ApplicationModel.defaultModel(), key, defaultValue);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String)}
*/
@Deprecated
public static String getDynamicProperty(String property) {
return getDynamicProperty(ApplicationModel.defaultModel(), property);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String, String)}
*/
@Deprecated
public static String getDynamicProperty(String property, String defaultValue) {
return getDynamicProperty(ApplicationModel.defaultModel(), property, defaultValue);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String)}
*/
@Deprecated
public static String getProperty(String property) {
return getProperty(ApplicationModel.defaultModel(), property);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String, String)}
*/
@Deprecated
public static String getProperty(String property, String defaultValue) {
return getProperty(ApplicationModel.defaultModel(), property, defaultValue);
}
/**
* For compact single instance
*
* @deprecated Replaced to {@link ConfigurationUtils#get(ScopeModel, String, int)}
*/
@Deprecated
public static int get(String property, int defaultValue) {
return get(ApplicationModel.defaultModel(), property, defaultValue);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.context.ApplicationExt;
import org.apache.dubbo.common.context.LifecycleAdapter;
import org.apache.dubbo.common.extension.DisableInject;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.context.ConfigConfigurationAdapter;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
public class Environment extends LifecycleAdapter implements ApplicationExt {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Environment.class);
public static final String NAME = "environment";
// dubbo properties in classpath
private PropertiesConfiguration propertiesConfiguration;
// java system props (-D)
private SystemConfiguration systemConfiguration;
// java system environment
private EnvironmentConfiguration environmentConfiguration;
// external config, such as config-center global/default config
private InmemoryConfiguration externalConfiguration;
// external app config, such as config-center app config
private InmemoryConfiguration appExternalConfiguration;
// local app config , such as Spring Environment/PropertySources/application.properties
private InmemoryConfiguration appConfiguration;
protected CompositeConfiguration globalConfiguration;
protected List<Map<String, String>> globalConfigurationMaps;
private CompositeConfiguration defaultDynamicGlobalConfiguration;
private DynamicConfiguration defaultDynamicConfiguration;
private String localMigrationRule;
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final ScopeModel scopeModel;
public Environment(ScopeModel scopeModel) {
this.scopeModel = scopeModel;
}
@Override
public void initialize() throws IllegalStateException {
if (initialized.compareAndSet(false, true)) {
this.propertiesConfiguration = new PropertiesConfiguration(scopeModel);
this.systemConfiguration = new SystemConfiguration();
this.environmentConfiguration = new EnvironmentConfiguration();
this.externalConfiguration = new InmemoryConfiguration("ExternalConfig");
this.appExternalConfiguration = new InmemoryConfiguration("AppExternalConfig");
this.appConfiguration = new InmemoryConfiguration("AppConfig");
loadMigrationRule();
}
}
/**
* @deprecated MigrationRule will be removed in 3.1
*/
@Deprecated
private void loadMigrationRule() {
if (Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(
CommonConstants.DubboProperty.DUBBO_MIGRATION_FILE_ENABLE, "false"))) {
String path =
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_MIGRATION_KEY);
if (StringUtils.isEmpty(path)) {
path = System.getenv(CommonConstants.DubboProperty.DUBBO_MIGRATION_KEY);
if (StringUtils.isEmpty(path)) {
path = CommonConstants.DEFAULT_DUBBO_MIGRATION_FILE;
}
}
this.localMigrationRule = ConfigUtils.loadMigrationRule(scopeModel.getClassLoaders(), path);
} else {
this.localMigrationRule = null;
}
}
/**
* @deprecated only for ut
*/
@Deprecated
@DisableInject
public void setLocalMigrationRule(String localMigrationRule) {
this.localMigrationRule = localMigrationRule;
}
@DisableInject
public void setExternalConfigMap(Map<String, String> externalConfiguration) {
if (externalConfiguration != null) {
this.externalConfiguration.setProperties(externalConfiguration);
}
}
@DisableInject
public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) {
if (appExternalConfiguration != null) {
this.appExternalConfiguration.setProperties(appExternalConfiguration);
}
}
@DisableInject
public void setAppConfigMap(Map<String, String> appConfiguration) {
if (appConfiguration != null) {
this.appConfiguration.setProperties(appConfiguration);
}
}
public Map<String, String> getExternalConfigMap() {
return externalConfiguration.getProperties();
}
public Map<String, String> getAppExternalConfigMap() {
return appExternalConfiguration.getProperties();
}
public Map<String, String> getAppConfigMap() {
return appConfiguration.getProperties();
}
public void updateExternalConfigMap(Map<String, String> externalMap) {
this.externalConfiguration.addProperties(externalMap);
}
public void updateAppExternalConfigMap(Map<String, String> externalMap) {
this.appExternalConfiguration.addProperties(externalMap);
}
/**
* Merge target map properties into app configuration
*
* @param map
*/
public void updateAppConfigMap(Map<String, String> map) {
this.appConfiguration.addProperties(map);
}
/**
* At start-up, Dubbo is driven by various configuration, such as Application, Registry, Protocol, etc.
* All configurations will be converged into a data bus - URL, and then drive the subsequent process.
* <p>
* At present, there are many configuration sources, including AbstractConfig (API, XML, annotation), - D, config center, etc.
* This method helps us t filter out the most priority values from various configuration sources.
*
* @param config
* @param prefix
* @return
*/
public Configuration getPrefixedConfiguration(AbstractConfig config, String prefix) {
// The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration ->
// ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration
Configuration instanceConfiguration = new ConfigConfigurationAdapter(config, prefix);
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(systemConfiguration);
compositeConfiguration.addConfiguration(environmentConfiguration);
compositeConfiguration.addConfiguration(appExternalConfiguration);
compositeConfiguration.addConfiguration(externalConfiguration);
compositeConfiguration.addConfiguration(appConfiguration);
compositeConfiguration.addConfiguration(instanceConfiguration);
compositeConfiguration.addConfiguration(propertiesConfiguration);
return new PrefixedConfiguration(compositeConfiguration, prefix);
}
/**
* There are two ways to get configuration during exposure / reference or at runtime:
* 1. URL, The value in the URL is relatively fixed. we can get value directly.
* 2. The configuration exposed in this method is convenient for us to query the latest values from multiple
* prioritized sources, it also guarantees that configs changed dynamically can take effect on the fly.
*/
public CompositeConfiguration getConfiguration() {
if (globalConfiguration == null) {
CompositeConfiguration configuration = new CompositeConfiguration();
configuration.addConfiguration(systemConfiguration);
configuration.addConfiguration(environmentConfiguration);
configuration.addConfiguration(appExternalConfiguration);
configuration.addConfiguration(externalConfiguration);
configuration.addConfiguration(appConfiguration);
configuration.addConfiguration(propertiesConfiguration);
globalConfiguration = configuration;
}
return globalConfiguration;
}
/**
* Get configuration map list for target instance
*
* @param config
* @param prefix
* @return
*/
public List<Map<String, String>> getConfigurationMaps(AbstractConfig config, String prefix) {
// The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration ->
// ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration
List<Map<String, String>> maps = new ArrayList<>();
maps.add(systemConfiguration.getProperties());
maps.add(environmentConfiguration.getProperties());
maps.add(appExternalConfiguration.getProperties());
maps.add(externalConfiguration.getProperties());
maps.add(appConfiguration.getProperties());
if (config != null) {
ConfigConfigurationAdapter configurationAdapter = new ConfigConfigurationAdapter(config, prefix);
maps.add(configurationAdapter.getProperties());
}
maps.add(propertiesConfiguration.getProperties());
return maps;
}
/**
* Get global configuration as map list
*
* @return
*/
public List<Map<String, String>> getConfigurationMaps() {
if (globalConfigurationMaps == null) {
globalConfigurationMaps = getConfigurationMaps(null, null);
}
return globalConfigurationMaps;
}
@Override
public void destroy() throws IllegalStateException {
initialized.set(false);
systemConfiguration = null;
propertiesConfiguration = null;
environmentConfiguration = null;
externalConfiguration = null;
appExternalConfiguration = null;
appConfiguration = null;
globalConfiguration = null;
globalConfigurationMaps = null;
defaultDynamicGlobalConfiguration = null;
if (defaultDynamicConfiguration != null) {
try {
defaultDynamicConfiguration.close();
} catch (Exception e) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"close dynamic configuration failed: " + e.getMessage(),
e);
}
defaultDynamicConfiguration = null;
}
}
/**
* Reset environment.
* For test only.
*/
public void reset() {
destroy();
initialize();
}
public String resolvePlaceholders(String str) {
return ConfigUtils.replaceProperty(str, getConfiguration());
}
public PropertiesConfiguration getPropertiesConfiguration() {
return propertiesConfiguration;
}
public SystemConfiguration getSystemConfiguration() {
return systemConfiguration;
}
public EnvironmentConfiguration getEnvironmentConfiguration() {
return environmentConfiguration;
}
public InmemoryConfiguration getExternalConfiguration() {
return externalConfiguration;
}
public InmemoryConfiguration getAppExternalConfiguration() {
return appExternalConfiguration;
}
public InmemoryConfiguration getAppConfiguration() {
return appConfiguration;
}
public String getLocalMigrationRule() {
return localMigrationRule;
}
public synchronized void refreshClassLoaders() {
propertiesConfiguration.refresh();
loadMigrationRule();
this.globalConfiguration = null;
this.globalConfigurationMaps = null;
this.defaultDynamicGlobalConfiguration = null;
}
public Configuration getDynamicGlobalConfiguration() {
if (defaultDynamicGlobalConfiguration == null) {
if (defaultDynamicConfiguration == null) {
if (logger.isWarnEnabled()) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"dynamicConfiguration is null , return globalConfiguration.");
}
return getConfiguration();
}
defaultDynamicGlobalConfiguration = new CompositeConfiguration();
defaultDynamicGlobalConfiguration.addConfiguration(defaultDynamicConfiguration);
defaultDynamicGlobalConfiguration.addConfiguration(getConfiguration());
}
return defaultDynamicGlobalConfiguration;
}
public Optional<DynamicConfiguration> getDynamicConfiguration() {
return Optional.ofNullable(defaultDynamicConfiguration);
}
@DisableInject
public void setDynamicConfiguration(DynamicConfiguration defaultDynamicConfiguration) {
this.defaultDynamicConfiguration = defaultDynamicConfiguration;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* In-memory configuration
*/
public class InmemoryConfiguration implements Configuration {
private String name;
// stores the configuration key-value pairs
private Map<String, String> store = new LinkedHashMap<>();
public InmemoryConfiguration() {}
public InmemoryConfiguration(String name) {
this.name = name;
}
public InmemoryConfiguration(Map<String, String> properties) {
this.setProperties(properties);
}
@Override
public Object getInternalProperty(String key) {
return store.get(key);
}
/**
* Add one property into the store, the previous value will be replaced if the key exists
*/
public void addProperty(String key, String value) {
store.put(key, value);
}
/**
* Add a set of properties into the store
*/
public void addProperties(Map<String, String> properties) {
if (properties != null) {
this.store.putAll(properties);
}
}
/**
* set store
*/
public void setProperties(Map<String, String> properties) {
if (properties != null) {
this.store = properties;
}
}
public Map<String, String> getProperties() {
return store;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class OrderedPropertiesConfiguration implements Configuration {
private Properties properties;
private final ModuleModel moduleModel;
public OrderedPropertiesConfiguration(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
refresh();
}
public void refresh() {
properties = new Properties();
ExtensionLoader<OrderedPropertiesProvider> propertiesProviderExtensionLoader =
moduleModel.getExtensionLoader(OrderedPropertiesProvider.class);
Set<String> propertiesProviderNames = propertiesProviderExtensionLoader.getSupportedExtensions();
if (CollectionUtils.isEmpty(propertiesProviderNames)) {
return;
}
List<OrderedPropertiesProvider> orderedPropertiesProviders = new ArrayList<>();
for (String propertiesProviderName : propertiesProviderNames) {
orderedPropertiesProviders.add(propertiesProviderExtensionLoader.getExtension(propertiesProviderName));
}
// order the propertiesProvider according the priority descending
orderedPropertiesProviders.sort((a, b) -> b.priority() - a.priority());
// override the properties.
for (OrderedPropertiesProvider orderedPropertiesProvider : orderedPropertiesProviders) {
properties.putAll(orderedPropertiesProvider.initProperties());
}
}
@Override
public String getProperty(String key) {
return properties.getProperty(key);
}
@Override
public Object getInternalProperty(String key) {
return properties.getProperty(key);
}
public void setProperty(String key, String value) {
properties.setProperty(key, value);
}
public String remove(String key) {
return (String) properties.remove(key);
}
/**
* For ut only
*/
@Deprecated
public void setProperties(Properties properties) {
this.properties = properties;
}
public Map<String, String> getProperties() {
return (Map) properties;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.Map;
/**
* Configuration from system properties
*/
public class SystemConfiguration implements Configuration {
@Override
public Object getInternalProperty(String key) {
return System.getProperty(key);
}
public Map<String, String> getProperties() {
return (Map) System.getProperties();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Collection;
import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.common.utils.PathUtils.normalize;
/**
* An abstract implementation of {@link DynamicConfiguration} is like "tree-structure" path :
* <ul>
* <li>{@link org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration "file"}</li>
* <li>{@link org.apache.dubbo.configcenter.support.zookeeper.ZookeeperDynamicConfiguration "zookeeper"}</li>
* </ul>
*
* @see DynamicConfiguration
* @see AbstractDynamicConfiguration
* @since 2.7.8
*/
public abstract class TreePathDynamicConfiguration extends AbstractDynamicConfiguration {
/**
* The parameter name of URL for the config root path
*/
public static final String CONFIG_ROOT_PATH_PARAM_NAME = PARAM_NAME_PREFIX + "root-path";
/**
* The parameter name of URL for the config base path
*/
public static final String CONFIG_BASE_PATH_PARAM_NAME = PARAM_NAME_PREFIX + "base-path";
/**
* The default value of parameter of URL for the config base path
*/
public static final String DEFAULT_CONFIG_BASE_PATH = "/config";
protected final String rootPath;
public TreePathDynamicConfiguration(URL url) {
super(url);
this.rootPath = getRootPath(url);
}
public TreePathDynamicConfiguration(
String rootPath,
String threadPoolPrefixName,
int threadPoolSize,
long keepAliveTime,
String group,
long timeout) {
super(threadPoolPrefixName, threadPoolSize, keepAliveTime, group, timeout);
this.rootPath = rootPath;
}
@Override
protected final String doGetConfig(String key, String group) throws Exception {
String pathKey = buildPathKey(group, key);
return doGetConfig(pathKey);
}
@Override
public final boolean publishConfig(String key, String group, String content) {
String pathKey = buildPathKey(group, key);
return Boolean.TRUE.equals(execute(() -> doPublishConfig(pathKey, content), getDefaultTimeout()));
}
@Override
protected final boolean doRemoveConfig(String key, String group) throws Exception {
String pathKey = buildPathKey(group, key);
return doRemoveConfig(pathKey);
}
@Override
public final void addListener(String key, String group, ConfigurationListener listener) {
String pathKey = buildPathKey(group, key);
doAddListener(pathKey, listener, key, group);
}
@Override
public final void removeListener(String key, String group, ConfigurationListener listener) {
String pathKey = buildPathKey(group, key);
doRemoveListener(pathKey, listener);
}
protected abstract boolean doPublishConfig(String pathKey, String content) throws Exception;
protected abstract String doGetConfig(String pathKey) throws Exception;
protected abstract boolean doRemoveConfig(String pathKey) throws Exception;
protected abstract Collection<String> doGetConfigKeys(String groupPath);
protected abstract void doAddListener(String pathKey, ConfigurationListener listener, String key, String group);
protected abstract void doRemoveListener(String pathKey, ConfigurationListener listener);
protected String buildGroupPath(String group) {
return buildPath(rootPath, group);
}
protected String buildPathKey(String group, String key) {
return buildPath(buildGroupPath(group), key);
}
/**
* Get the root path from the specified {@link URL connection URl}
*
* @param url the specified {@link URL connection URl}
* @return non-null
*/
protected String getRootPath(URL url) {
String rootPath = url.getParameter(CONFIG_ROOT_PATH_PARAM_NAME, buildRootPath(url));
rootPath = normalize(rootPath);
int rootPathLength = rootPath.length();
if (rootPathLength > 1 && rootPath.endsWith(PATH_SEPARATOR)) {
rootPath = rootPath.substring(0, rootPathLength - 1);
}
return rootPath;
}
private String buildRootPath(URL url) {
return PATH_SEPARATOR + getConfigNamespace(url) + getConfigBasePath(url);
}
/**
* Get the namespace from the specified {@link URL connection URl}
*
* @param url the specified {@link URL connection URl}
* @return non-null
*/
protected String getConfigNamespace(URL url) {
return url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP);
}
/**
* Get the config base path from the specified {@link URL connection URl}
*
* @param url the specified {@link URL connection URl}
* @return non-null
*/
protected String getConfigBasePath(URL url) {
String configBasePath = url.getParameter(CONFIG_BASE_PATH_PARAM_NAME, DEFAULT_CONFIG_BASE_PATH);
if (StringUtils.isNotEmpty(configBasePath) && !configBasePath.startsWith(PATH_SEPARATOR)) {
configBasePath = PATH_SEPARATOR + configBasePath;
}
return configBasePath;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
/**
* Config change event type
*/
public enum ConfigChangeType {
/**
* A config is created.
*/
ADDED,
/**
* A config is updated.
*/
MODIFIED,
/**
* A config is deleted.
*/
DELETED
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
/**
* The abstract implementation of {@link DynamicConfiguration}
*
* @since 2.7.5
*/
public abstract class AbstractDynamicConfiguration implements DynamicConfiguration {
public static final String PARAM_NAME_PREFIX = "dubbo.config-center.";
public static final String THREAD_POOL_PREFIX_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.prefix";
public static final String DEFAULT_THREAD_POOL_PREFIX = PARAM_NAME_PREFIX + "workers";
public static final String THREAD_POOL_SIZE_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.size";
/**
* The keep alive time in milliseconds for threads in {@link ThreadPoolExecutor}
*/
public static final String THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME =
PARAM_NAME_PREFIX + "thread-pool.keep-alive-time";
/**
* The parameter name of group for config-center
*
* @since 2.7.8
*/
public static final String GROUP_PARAM_NAME = PARAM_NAME_PREFIX + GROUP_KEY;
/**
* The parameter name of timeout for config-center
*
* @since 2.7.8
*/
public static final String TIMEOUT_PARAM_NAME = PARAM_NAME_PREFIX + TIMEOUT_KEY;
public static final int DEFAULT_THREAD_POOL_SIZE = 1;
/**
* Default keep alive time in milliseconds for threads in {@link ThreadPoolExecutor} is 1 minute( 60 * 1000 ms)
*/
public static final long DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME = TimeUnit.MINUTES.toMillis(1);
/**
* Logger
*/
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* The thread pool for workers who execute the tasks
*/
private final ThreadPoolExecutor workersThreadPool;
private final String group;
private final long timeout;
protected AbstractDynamicConfiguration(URL url) {
this(
getThreadPoolPrefixName(url),
getThreadPoolSize(url),
getThreadPoolKeepAliveTime(url),
getGroup(url),
getTimeout(url));
}
protected AbstractDynamicConfiguration(
String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, String group, long timeout) {
this.workersThreadPool = initWorkersThreadPool(threadPoolPrefixName, threadPoolSize, keepAliveTime);
this.group = group;
this.timeout = timeout;
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {}
@Override
public final String getConfig(String key, String group, long timeout) throws IllegalStateException {
return execute(() -> doGetConfig(key, group), timeout);
}
@Override
public Object getInternalProperty(String key) {
return null;
}
@Override
public final void close() throws Exception {
try {
doClose();
} finally {
doFinally();
}
}
@Override
public boolean removeConfig(String key, String group) {
return Boolean.TRUE.equals(execute(() -> doRemoveConfig(key, group), -1L));
}
/**
* @return the default group
* @since 2.7.8
*/
@Override
public String getDefaultGroup() {
return getGroup();
}
/**
* @return the default timeout
* @since 2.7.8
*/
@Override
public long getDefaultTimeout() {
return getTimeout();
}
/**
* Get the content of configuration in the specified key and group
*
* @param key the key
* @param group the group
* @return if found, return the content of configuration
* @throws Exception If met with some problems
*/
protected abstract String doGetConfig(String key, String group) throws Exception;
/**
* Close the resources if necessary
*
* @throws Exception If met with some problems
*/
protected abstract void doClose() throws Exception;
/**
* Remove the config in the specified key and group
*
* @param key the key
* @param group the group
* @return If successful, return <code>true</code>, or <code>false</code>
* @throws Exception
* @since 2.7.8
*/
protected abstract boolean doRemoveConfig(String key, String group) throws Exception;
/**
* Executes the {@link Runnable} with the specified timeout
*
* @param task the {@link Runnable task}
* @param timeout timeout in milliseconds
*/
protected final void execute(Runnable task, long timeout) {
execute(
() -> {
task.run();
return null;
},
timeout);
}
/**
* Executes the {@link Callable} with the specified timeout
*
* @param task the {@link Callable task}
* @param timeout timeout in milliseconds
* @param <V> the type of computing result
* @return the computing result
*/
protected final <V> V execute(Callable<V> task, long timeout) {
V value = null;
try {
if (timeout < 1) { // less or equal 0
value = task.call();
} else {
Future<V> future = workersThreadPool.submit(task);
value = future.get(timeout, TimeUnit.MILLISECONDS);
}
} catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e);
}
}
return value;
}
protected ThreadPoolExecutor getWorkersThreadPool() {
return workersThreadPool;
}
private void doFinally() {
shutdownWorkersThreadPool();
}
private void shutdownWorkersThreadPool() {
if (!workersThreadPool.isShutdown()) {
workersThreadPool.shutdown();
}
}
protected ThreadPoolExecutor initWorkersThreadPool(
String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) {
return new ThreadPoolExecutor(
threadPoolSize,
threadPoolSize,
keepAliveTime,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
new NamedThreadFactory(threadPoolPrefixName, true));
}
protected static String getThreadPoolPrefixName(URL url) {
return getParameter(url, THREAD_POOL_PREFIX_PARAM_NAME, DEFAULT_THREAD_POOL_PREFIX);
}
protected static int getThreadPoolSize(URL url) {
return getParameter(url, THREAD_POOL_SIZE_PARAM_NAME, DEFAULT_THREAD_POOL_SIZE);
}
protected static long getThreadPoolKeepAliveTime(URL url) {
return getParameter(url, THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME);
}
protected static String getParameter(URL url, String name, String defaultValue) {
if (url != null) {
return url.getParameter(name, defaultValue);
}
return defaultValue;
}
protected static int getParameter(URL url, String name, int defaultValue) {
if (url != null) {
return url.getParameter(name, defaultValue);
}
return defaultValue;
}
protected static long getParameter(URL url, String name, long defaultValue) {
if (url != null) {
return url.getParameter(name, defaultValue);
}
return defaultValue;
}
protected String getGroup() {
return group;
}
protected long getTimeout() {
return timeout;
}
/**
* Get the group from {@link URL the specified connection URL}
*
* @param url {@link URL the specified connection URL}
* @return non-null
* @since 2.7.8
*/
protected static String getGroup(URL url) {
String group = getParameter(url, GROUP_PARAM_NAME, null);
return StringUtils.isBlank(group) ? getParameter(url, GROUP_KEY, DEFAULT_GROUP) : group;
}
/**
* Get the timeout from {@link URL the specified connection URL}
*
* @param url {@link URL the specified connection URL}
* @return non-null
* @since 2.7.8
*/
protected static long getTimeout(URL url) {
return getParameter(url, TIMEOUT_PARAM_NAME, -1L);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import java.util.EventObject;
import java.util.Objects;
/**
* An event raised when the config changed, immutable.
*
* @see ConfigChangeType
*/
public class ConfigChangedEvent extends EventObject {
private final String key;
private final String group;
private final String content;
private final ConfigChangeType changeType;
public ConfigChangedEvent(String key, String group, String content) {
this(key, group, content, ConfigChangeType.MODIFIED);
}
public ConfigChangedEvent(String key, String group, String content, ConfigChangeType changeType) {
super(key + "," + group);
this.key = key;
this.group = group;
this.content = content;
this.changeType = changeType;
}
public String getKey() {
return key;
}
public String getGroup() {
return group;
}
public String getContent() {
return content;
}
public ConfigChangeType getChangeType() {
return changeType;
}
@Override
public String toString() {
return "ConfigChangedEvent{" + "key='"
+ key + '\'' + ", group='"
+ group + '\'' + ", content='"
+ content + '\'' + ", changeType="
+ changeType + "} "
+ super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ConfigChangedEvent)) {
return false;
}
ConfigChangedEvent that = (ConfigChangedEvent) o;
return Objects.equals(getKey(), that.getKey())
&& Objects.equals(getGroup(), that.getGroup())
&& Objects.equals(getContent(), that.getContent())
&& getChangeType() == that.getChangeType();
}
@Override
public int hashCode() {
return Objects.hash(getKey(), getGroup(), getContent(), getChangeType());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
/**
* Abstract {@link DynamicConfigurationFactory} implementation with cache ability
*
* @see DynamicConfigurationFactory
* @since 2.7.5
*/
public abstract class AbstractDynamicConfigurationFactory implements DynamicConfigurationFactory {
private volatile ConcurrentHashMap<String, DynamicConfiguration> dynamicConfigurations = new ConcurrentHashMap<>();
@Override
public final DynamicConfiguration getDynamicConfiguration(URL url) {
String key = url == null ? DEFAULT_KEY : url.toServiceString();
return ConcurrentHashMapUtils.computeIfAbsent(dynamicConfigurations, key, k -> createDynamicConfiguration(url));
}
protected abstract DynamicConfiguration createDynamicConfiguration(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
/**
* Dynamic Configuration
* <br/>
* From the use scenario internally inside framework, there are mainly three kinds of methods:
* <ol>
* <li>{@link #getProperties(String, String, long)}, get configuration file from Config Center at start up.</li>
* <li>{@link #addListener(String, String, ConfigurationListener)}/ {@link #removeListener(String, String, ConfigurationListener)}
* , add or remove listeners for governance rules or config items that need to watch.</li>
* <li>{@link #getProperty(String, Object)}, get a single config item.</li>
* <li>{@link #getConfig(String, String, long)}, get the specified config</li>
* </ol>
*
* @see AbstractDynamicConfiguration
*/
public interface DynamicConfiguration extends Configuration, AutoCloseable {
String DEFAULT_GROUP = "dubbo";
/**
* {@link #addListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void addListener(String key, ConfigurationListener listener) {
addListener(key, getDefaultGroup(), listener);
}
/**
* {@link #removeListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void removeListener(String key, ConfigurationListener listener) {
removeListener(key, getDefaultGroup(), listener);
}
/**
* Register a configuration listener for a specified key
* The listener only works for service governance purpose, so the target group would always be the value user
* specifies at startup or 'dubbo' by default. This method will only register listener, which means it will not
* trigger a notification that contains the current value.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void addListener(String key, String group, ConfigurationListener listener);
/**
* Stops one listener from listening to value changes in the specified key.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void removeListener(String key, String group, ConfigurationListener listener);
/**
* Get the configuration mapped to the given key and the given group with {@link #getDefaultTimeout() the default
* timeout}
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @return target configuration mapped to the given key and the given group
*/
default String getConfig(String key, String group) {
return getConfig(key, group, getDefaultTimeout());
}
/**
* get configItem which contains content and stat info.
*
* @param key
* @param group
* @return
*/
default ConfigItem getConfigItem(String key, String group) {
String content = getConfig(key, group);
return new ConfigItem(content, null);
}
/**
* Get the configuration mapped to the given key and the given group. If the
* configuration fails to fetch after timeout exceeds, IllegalStateException will be thrown.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param timeout timeout value for fetching the target config
* @return target configuration mapped to the given key and the given group, IllegalStateException will be thrown
* if timeout exceeds.
*/
String getConfig(String key, String group, long timeout) throws IllegalStateException;
/**
* This method are mostly used to get a compound config file with {@link #getDefaultTimeout() the default timeout},
* such as a complete dubbo.properties file.
*/
default String getProperties(String key, String group) throws IllegalStateException {
return getProperties(key, group, getDefaultTimeout());
}
/**
* This method are mostly used to get a compound config file, such as a complete dubbo.properties file.
*
* @revision 2.7.4
*/
default String getProperties(String key, String group, long timeout) throws IllegalStateException {
return getConfig(key, group, timeout);
}
/**
* Publish Config mapped to the given key under the {@link #getDefaultGroup() default group}
*
* @param key the key to represent a configuration
* @param content the content of configuration
* @return <code>true</code> if success, or <code>false</code>
* @throws UnsupportedOperationException If the under layer does not support
* @since 2.7.5
*/
default boolean publishConfig(String key, String content) throws UnsupportedOperationException {
return publishConfig(key, getDefaultGroup(), content);
}
/**
* Publish Config mapped to the given key and the given group.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param content the content of configuration
* @return <code>true</code> if success, or <code>false</code>
* @throws UnsupportedOperationException If the under layer does not support
* @since 2.7.5
*/
default boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException {
return false;
}
/**
* publish config mapped to this given key and given group with stat.
*
* @param key
* @param group
* @param content
* @param ticket
* @return
* @throws UnsupportedOperationException
*/
default boolean publishConfigCas(String key, String group, String content, Object ticket)
throws UnsupportedOperationException {
return false;
}
/**
* Get the default group for the operations
*
* @return The default value is {@link #DEFAULT_GROUP "dubbo"}
* @since 2.7.5
*/
default String getDefaultGroup() {
return DEFAULT_GROUP;
}
/**
* Get the default timeout for the operations in milliseconds
*
* @return The default value is <code>-1L</code>
* @since 2.7.5
*/
default long getDefaultTimeout() {
return -1L;
}
/**
* Close the configuration
*
* @throws Exception
* @since 2.7.5
*/
@Override
default void close() throws Exception {
throw new UnsupportedOperationException();
}
/**
* The format is '{interfaceName}:[version]:[group]'
*
* @return
*/
static String getRuleKey(URL url) {
return url.getColonSeparatedKey();
}
/**
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @return <code>true</code> if success, or <code>false</code>
* @since 2.7.8
*/
default boolean removeConfig(String key, String group) {
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
/**
* @deprecated Replaced to {@link org.apache.dubbo.common.constants.CommonConstants}
*/
@Deprecated
public interface Constants {
String CONFIG_CLUSTER_KEY = "config.cluster";
String CONFIG_NAMESPACE_KEY = "config.namespace";
String CONFIG_GROUP_KEY = "config.group";
String CONFIG_CHECK_KEY = "config.check";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import java.util.EventListener;
/**
* Config listener, will get notified when the config it listens on changes.
*/
public interface ConfigurationListener extends EventListener {
/**
* Listener call back method. Listener gets notified by this method once there's any change happens on the config
* the listener listens on.
*
* @param event config change event
*/
void process(ConfigChangedEvent event);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
/**
* Hold content and version information
*/
public class ConfigItem {
/**
* configure item content.
*/
private String content;
/**
* version information corresponding to the current configure item.
*/
private Object ticket;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Object getTicket() {
return ticket;
}
public void setTicket(Object ticket) {
this.ticket = ticket;
}
public ConfigItem(String content, Object ticket) {
this.content = content;
this.ticket = ticket;
}
public ConfigItem() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* The factory interface to create the instance of {@link DynamicConfiguration}
*/
@SPI(value = "nop", scope = ExtensionScope.APPLICATION) // 2.7.5 change the default SPI implementation
public interface DynamicConfigurationFactory {
DynamicConfiguration getDynamicConfiguration(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter.nop;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
@Deprecated
public class NopDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
return new NopDynamicConfiguration(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter.nop;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
/**
* The default extension of {@link DynamicConfiguration}. If user does not specify a config center, or specifies one
* that is not a valid extension, it will default to this one.
*/
@Deprecated
public class NopDynamicConfiguration implements DynamicConfiguration {
public NopDynamicConfiguration(URL url) {
// no-op
}
@Override
public Object getInternalProperty(String key) {
return null;
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
// no-op
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
// no-op
}
@Override
public String getConfig(String key, String group, long timeout) throws IllegalStateException {
// no-op
return null;
}
/**
* @since 2.7.5
*/
@Override
public boolean publishConfig(String key, String group, String content) {
return true;
}
@Override
public void close() throws Exception {
// no-op
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java | dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter.wrapper;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
/**
* support multiple config center, simply iterating each concrete config center.
*/
public class CompositeDynamicConfiguration implements DynamicConfiguration {
public static final String NAME = "COMPOSITE";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(CompositeDynamicConfiguration.class);
private final Set<DynamicConfiguration> configurations = new HashSet<>();
public void addConfiguration(DynamicConfiguration configuration) {
if (configuration != null) {
this.configurations.add(configuration);
}
}
public Set<DynamicConfiguration> getInnerConfigurations() {
return configurations;
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
iterateListenerOperation(configuration -> configuration.addListener(key, group, listener));
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
iterateListenerOperation(configuration -> configuration.removeListener(key, group, listener));
}
@Override
public String getConfig(String key, String group, long timeout) throws IllegalStateException {
return (String) iterateConfigOperation(configuration -> configuration.getConfig(key, group, timeout));
}
@Override
public String getProperties(String key, String group, long timeout) throws IllegalStateException {
return (String) iterateConfigOperation(configuration -> configuration.getProperties(key, group, timeout));
}
@Override
public Object getInternalProperty(String key) {
return iterateConfigOperation(configuration -> configuration.getInternalProperty(key));
}
@Override
public boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException {
boolean publishedAll = true;
for (DynamicConfiguration configuration : configurations) {
if (!configuration.publishConfig(key, group, content)) {
publishedAll = false;
}
}
return publishedAll;
}
@Override
public void close() throws Exception {
for (DynamicConfiguration configuration : configurations) {
try {
configuration.close();
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"unknown error in configuration-center related code in common module",
"",
"close dynamic configuration "
+ configuration.getClass().getName() + "failed: " + e.getMessage(),
e);
}
}
configurations.clear();
}
private void iterateListenerOperation(Consumer<DynamicConfiguration> consumer) {
for (DynamicConfiguration configuration : configurations) {
consumer.accept(configuration);
}
}
private Object iterateConfigOperation(Function<DynamicConfiguration, Object> func) {
Object value = null;
for (DynamicConfiguration configuration : configurations) {
value = func.apply(configuration);
if (value != null) {
break;
}
}
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import java.lang.instrument.Instrumentation;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Can completely solve the OOM problem caused by {@link java.util.concurrent.LinkedBlockingQueue}.
*/
public class MemoryLimitedLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> {
private static final long serialVersionUID = 1374792064759926198L;
private final MemoryLimiter memoryLimiter;
public MemoryLimitedLinkedBlockingQueue(Instrumentation inst) {
this(Integer.MAX_VALUE, inst);
}
public MemoryLimitedLinkedBlockingQueue(long memoryLimit, Instrumentation inst) {
super(Integer.MAX_VALUE);
this.memoryLimiter = new MemoryLimiter(memoryLimit, inst);
}
public MemoryLimitedLinkedBlockingQueue(Collection<? extends E> c, long memoryLimit, Instrumentation inst) {
super(c);
this.memoryLimiter = new MemoryLimiter(memoryLimit, inst);
}
public void setMemoryLimit(long memoryLimit) {
memoryLimiter.setMemoryLimit(memoryLimit);
}
public long getMemoryLimit() {
return memoryLimiter.getMemoryLimit();
}
public long getCurrentMemory() {
return memoryLimiter.getCurrentMemory();
}
public long getCurrentRemainMemory() {
return memoryLimiter.getCurrentRemainMemory();
}
@Override
public void put(E e) throws InterruptedException {
memoryLimiter.acquireInterruptibly(e);
super.put(e);
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return memoryLimiter.acquire(e, timeout, unit) && super.offer(e, timeout, unit);
}
@Override
public boolean offer(E e) {
return memoryLimiter.acquire(e) && super.offer(e);
}
@Override
public E take() throws InterruptedException {
final E e = super.take();
memoryLimiter.releaseInterruptibly(e);
return e;
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
final E e = super.poll(timeout, unit);
memoryLimiter.releaseInterruptibly(e, timeout, unit);
return e;
}
@Override
public E poll() {
final E e = super.poll();
memoryLimiter.release(e);
return e;
}
@Override
public boolean remove(Object o) {
final boolean success = super.remove(o);
if (success) {
memoryLimiter.release(o);
}
return success;
}
@Override
public void clear() {
super.clear();
memoryLimiter.clear();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.resource.GlobalResourcesRepository;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* {@link java.lang.Runtime#freeMemory()} technology is used to calculate the
* memory limit by using the percentage of the current maximum available memory,
* which can be used with {@link MemoryLimiter}.
*
* @see MemoryLimiter
* @see <a href="https://github.com/apache/incubator-shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/concurrent/MemoryLimitCalculator.java">MemoryLimitCalculator</a>
*/
public class MemoryLimitCalculator {
private static volatile long maxAvailable;
private static final AtomicBoolean refreshStarted = new AtomicBoolean(false);
private static void refresh() {
maxAvailable = Runtime.getRuntime().freeMemory();
}
private static void checkAndScheduleRefresh() {
if (!refreshStarted.get()) {
// immediately refresh when first call to prevent maxAvailable from being 0
// to ensure that being refreshed before refreshStarted being set as true
// notice: refresh may be called for more than once because there is no lock
refresh();
if (refreshStarted.compareAndSet(false, true)) {
ScheduledExecutorService scheduledExecutorService =
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Memory-Calculator"));
// check every 50 ms to improve performance
scheduledExecutorService.scheduleWithFixedDelay(
MemoryLimitCalculator::refresh, 50, 50, TimeUnit.MILLISECONDS);
GlobalResourcesRepository.registerGlobalDisposable(() -> {
refreshStarted.set(false);
scheduledExecutorService.shutdown();
});
}
}
}
/**
* Get the maximum available memory of the current JVM.
*
* @return maximum available memory
*/
public static long maxAvailable() {
checkAndScheduleRefresh();
return maxAvailable;
}
/**
* Take the current JVM's maximum available memory
* as a percentage of the result as the limit.
*
* @param percentage percentage
* @return available memory
*/
public static long calculate(final float percentage) {
if (percentage <= 0 || percentage > 1) {
throw new IllegalArgumentException();
}
checkAndScheduleRefresh();
return (long) (maxAvailable() * percentage);
}
/**
* By default, it takes 80% of the maximum available memory of the current JVM.
*
* @return available memory
*/
public static long defaultLimit() {
checkAndScheduleRefresh();
return (long) (maxAvailable() * 0.8);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* memory limiter.
*/
public class MemoryLimiter {
private final Instrumentation inst;
private long memoryLimit;
private final LongAdder memory = new LongAdder();
private final ReentrantLock acquireLock = new ReentrantLock();
private final Condition notLimited = acquireLock.newCondition();
private final ReentrantLock releaseLock = new ReentrantLock();
private final Condition notEmpty = releaseLock.newCondition();
public MemoryLimiter(Instrumentation inst) {
this(Integer.MAX_VALUE, inst);
}
public MemoryLimiter(long memoryLimit, Instrumentation inst) {
if (memoryLimit <= 0) {
throw new IllegalArgumentException();
}
this.memoryLimit = memoryLimit;
this.inst = inst;
}
public void setMemoryLimit(long memoryLimit) {
if (memoryLimit <= 0) {
throw new IllegalArgumentException();
}
this.memoryLimit = memoryLimit;
}
public long getMemoryLimit() {
return memoryLimit;
}
public long getCurrentMemory() {
return memory.sum();
}
public long getCurrentRemainMemory() {
return getMemoryLimit() - getCurrentMemory();
}
private void signalNotEmpty() {
releaseLock.lock();
try {
notEmpty.signal();
} finally {
releaseLock.unlock();
}
}
private void signalNotLimited() {
acquireLock.lock();
try {
notLimited.signal();
} finally {
acquireLock.unlock();
}
}
/**
* Locks to prevent both acquires and releases.
*/
private void fullyLock() {
acquireLock.lock();
releaseLock.lock();
}
/**
* Unlocks to allow both acquires and releases.
*/
private void fullyUnlock() {
releaseLock.unlock();
acquireLock.unlock();
}
public boolean acquire(Object e) {
if (e == null) {
throw new NullPointerException();
}
if (memory.sum() >= memoryLimit) {
return false;
}
acquireLock.lock();
try {
final long sum = memory.sum();
final long objectSize = inst.getObjectSize(e);
if (sum + objectSize >= memoryLimit) {
return false;
}
memory.add(objectSize);
// see https://github.com/apache/incubator-shenyu/pull/3356
if (memory.sum() < memoryLimit) {
notLimited.signal();
}
} finally {
acquireLock.unlock();
}
if (memory.sum() > 0) {
signalNotEmpty();
}
return true;
}
public void acquireInterruptibly(Object e) throws InterruptedException {
if (e == null) {
throw new NullPointerException();
}
acquireLock.lockInterruptibly();
try {
final long objectSize = inst.getObjectSize(e);
// see https://github.com/apache/incubator-shenyu/pull/3335
while (memory.sum() + objectSize >= memoryLimit) {
notLimited.await();
}
memory.add(objectSize);
if (memory.sum() < memoryLimit) {
notLimited.signal();
}
} finally {
acquireLock.unlock();
}
if (memory.sum() > 0) {
signalNotEmpty();
}
}
public boolean acquire(Object e, long timeout, TimeUnit unit) throws InterruptedException {
if (e == null) {
throw new NullPointerException();
}
long nanos = unit.toNanos(timeout);
acquireLock.lockInterruptibly();
try {
final long objectSize = inst.getObjectSize(e);
while (memory.sum() + objectSize >= memoryLimit) {
if (nanos <= 0) {
return false;
}
nanos = notLimited.awaitNanos(nanos);
}
memory.add(objectSize);
if (memory.sum() < memoryLimit) {
notLimited.signal();
}
} finally {
acquireLock.unlock();
}
if (memory.sum() > 0) {
signalNotEmpty();
}
return true;
}
public void release(Object e) {
if (null == e) {
return;
}
if (memory.sum() == 0) {
return;
}
releaseLock.lock();
try {
final long objectSize = inst.getObjectSize(e);
if (memory.sum() > 0) {
memory.add(-objectSize);
if (memory.sum() > 0) {
notEmpty.signal();
}
}
} finally {
releaseLock.unlock();
}
if (memory.sum() < memoryLimit) {
signalNotLimited();
}
}
public void releaseInterruptibly(Object e) throws InterruptedException {
if (null == e) {
return;
}
releaseLock.lockInterruptibly();
try {
final long objectSize = inst.getObjectSize(e);
while (memory.sum() == 0) {
notEmpty.await();
}
memory.add(-objectSize);
if (memory.sum() > 0) {
notEmpty.signal();
}
} finally {
releaseLock.unlock();
}
if (memory.sum() < memoryLimit) {
signalNotLimited();
}
}
public void releaseInterruptibly(Object e, long timeout, TimeUnit unit) throws InterruptedException {
if (null == e) {
return;
}
long nanos = unit.toNanos(timeout);
releaseLock.lockInterruptibly();
try {
final long objectSize = inst.getObjectSize(e);
while (memory.sum() == 0) {
if (nanos <= 0) {
return;
}
nanos = notEmpty.awaitNanos(nanos);
}
memory.add(-objectSize);
if (memory.sum() > 0) {
notEmpty.signal();
}
} finally {
releaseLock.unlock();
}
if (memory.sum() < memoryLimit) {
signalNotLimited();
}
}
public void clear() {
fullyLock();
try {
if (memory.sumThenReset() < memoryLimit) {
notLimited.signal();
}
} finally {
fullyUnlock();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.concurrent.DiscardPolicy;
import org.apache.dubbo.common.concurrent.Rejector;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Can completely solve the OOM problem caused by {@link java.util.concurrent.LinkedBlockingQueue},
* does not depend on {@link java.lang.instrument.Instrumentation} and is easier to use than
* {@link MemoryLimitedLinkedBlockingQueue}.
*
* @see <a href="https://github.com/apache/incubator-shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/concurrent/MemorySafeLinkedBlockingQueue.java">MemorySafeLinkedBlockingQueue</a>
*/
public class MemorySafeLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> {
private static final long serialVersionUID = 8032578371739960142L;
public static int THE_256_MB = 256 * 1024 * 1024;
private long maxFreeMemory;
private Rejector<E> rejector;
public MemorySafeLinkedBlockingQueue() {
this(THE_256_MB);
}
public MemorySafeLinkedBlockingQueue(final long maxFreeMemory) {
super(Integer.MAX_VALUE);
this.maxFreeMemory = maxFreeMemory;
// default as DiscardPolicy to ensure compatibility with the old version
this.rejector = new DiscardPolicy<>();
}
public MemorySafeLinkedBlockingQueue(final Collection<? extends E> c, final int maxFreeMemory) {
super(c);
this.maxFreeMemory = maxFreeMemory;
// default as DiscardPolicy to ensure compatibility with the old version
this.rejector = new DiscardPolicy<>();
}
/**
* set the max free memory.
*
* @param maxFreeMemory the max free memory
*/
public void setMaxFreeMemory(final int maxFreeMemory) {
this.maxFreeMemory = maxFreeMemory;
}
/**
* get the max free memory.
*
* @return the max free memory limit
*/
public long getMaxFreeMemory() {
return maxFreeMemory;
}
/**
* set the rejector.
*
* @param rejector the rejector
*/
public void setRejector(final Rejector<E> rejector) {
this.rejector = rejector;
}
/**
* determine if there is any remaining free memory.
*
* @return true if has free memory
*/
public boolean hasRemainedMemory() {
return MemoryLimitCalculator.maxAvailable() > maxFreeMemory;
}
@Override
public void put(final E e) throws InterruptedException {
if (hasRemainedMemory()) {
super.put(e);
} else {
rejector.reject(e, this);
}
}
@Override
public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
if (!hasRemainedMemory()) {
rejector.reject(e, this);
return false;
}
return super.offer(e, timeout, unit);
}
@Override
public boolean offer(final E e) {
if (!hasRemainedMemory()) {
rejector.reject(e, this);
return false;
}
return super.offer(e);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
// TODO which scope for ThreadPool? APPLICATION or FRAMEWORK
@SPI(value = "fixed", scope = ExtensionScope.FRAMEWORK)
public interface ThreadPool {
/**
* Thread pool
*
* @param url URL contains thread parameter
* @return thread pool
*/
@Adaptive({THREADPOOL_KEY})
Executor getExecutor(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
/**
* The most important difference between this Executor and other normal Executor is that this one doesn't manage
* any thread.
* <p>
* Tasks submitted to this executor through {@link #execute(Runnable)} will not get scheduled to a specific thread, though normal executors always do the schedule.
* Those tasks are stored in a blocking queue and will only be executed when a thread calls {@link #waitAndDrain()}, the thread executing the task
* is exactly the same as the one calling waitAndDrain.
*/
public class ThreadlessExecutor extends AbstractExecutorService {
private static final Logger logger = LoggerFactory.getLogger(ThreadlessExecutor.class.getName());
private static final Object SHUTDOWN = new Object();
private final Queue<Runnable> queue = new ConcurrentLinkedQueue<>();
/**
* Wait thread. It must be visible to other threads and does not need to be thread-safe
*/
private final AtomicReference<Object> waiter = new AtomicReference<>();
/**
* Waits until there is a task, executes the task and all queued tasks (if there're any). The task is either a normal
* response or a timeout response.
*/
public void waitAndDrain(long deadline) throws InterruptedException {
throwIfInterrupted();
Runnable runnable = queue.poll();
if (runnable == null) {
if (waiter.compareAndSet(null, Thread.currentThread())) {
try {
while ((runnable = queue.poll()) == null && waiter.get() == Thread.currentThread()) {
long restTime = deadline - System.nanoTime();
if (restTime <= 0) {
return;
}
LockSupport.parkNanos(this, restTime);
throwIfInterrupted();
}
} finally {
waiter.compareAndSet(Thread.currentThread(), null);
}
}
}
do {
if (runnable != null) {
runnable.run();
}
} while ((runnable = queue.poll()) != null);
}
private static void throwIfInterrupted() throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
/**
* If the calling thread is still waiting for a callback task, add the task into the blocking queue to wait for schedule.
* Otherwise, submit to shared callback executor directly.
*
* @param runnable
*/
@Override
public void execute(Runnable runnable) {
RunnableWrapper run = new RunnableWrapper(runnable);
queue.add(run);
Object waiter = this.waiter.get();
if (waiter != SHUTDOWN) {
LockSupport.unpark((Thread) waiter);
} else if (queue.remove(run)) {
throw new RejectedExecutionException();
}
}
/**
* The following methods are still not supported
*/
@Override
public void shutdown() {
shutdownNow();
}
@Override
public List<Runnable> shutdownNow() {
if (waiter.get() != SHUTDOWN) {
LockSupport.unpark((Thread) waiter.get());
}
waiter.set(SHUTDOWN);
Runnable runnable;
while ((runnable = queue.poll()) != null) {
runnable.run();
}
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return waiter.get() == SHUTDOWN;
}
@Override
public boolean isTerminated() {
return isShutdown();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
return false;
}
private static class RunnableWrapper implements Runnable {
private final Runnable runnable;
public RunnableWrapper(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
try {
runnable.run();
} catch (Throwable t) {
logger.info(t);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.JVMUtil;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import static java.lang.String.format;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_OS_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_POOL_EXHAUSTED_LISTENERS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_POOL_EXHAUSTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_CREATE_DUMP;
/**
* Abort Policy.
* Log warn info when abort.
*/
public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy {
protected static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbortPolicyWithReport.class);
private final String threadName;
private final URL url;
protected static volatile long lastPrintTime = 0;
private static final long TEN_MINUTES_MILLS = 10 * 60 * 1000;
private static final String WIN_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss";
private static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd_HH:mm:ss";
protected static Semaphore guard = new Semaphore(1);
private static final String USER_HOME =
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.USER_HOME);
private final Set<ThreadPoolExhaustedListener> listeners = new ConcurrentHashSet<>();
public AbortPolicyWithReport(String threadName, URL url) {
this.threadName = threadName;
this.url = url;
String threadPoolExhaustedListeners = url.getParameter(
THREAD_POOL_EXHAUSTED_LISTENERS_KEY, (String) url.getAttribute(THREAD_POOL_EXHAUSTED_LISTENERS_KEY));
Set<String> listenerKeys = StringUtils.splitToSet(threadPoolExhaustedListeners, COMMA_SEPARATOR_CHAR, true);
FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel();
ExtensionLoader<ThreadPoolExhaustedListener> extensionLoader =
frameworkModel.getExtensionLoader(ThreadPoolExhaustedListener.class);
listenerKeys.forEach(key -> {
if (extensionLoader.hasExtension(key)) {
addThreadPoolExhaustedEventListener(extensionLoader.getExtension(key));
}
});
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
String msg = String.format(
"Thread pool is EXHAUSTED!"
+ " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d),"
+ " Task: %d (completed: %d),"
+ " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!",
threadName,
e.getPoolSize(),
e.getActiveCount(),
e.getCorePoolSize(),
e.getMaximumPoolSize(),
e.getLargestPoolSize(),
e.getTaskCount(),
e.getCompletedTaskCount(),
e.isShutdown(),
e.isTerminated(),
e.isTerminating(),
url.getProtocol(),
url.getIp(),
url.getPort());
// 0-1 - Thread pool is EXHAUSTED!
logger.warn(COMMON_THREAD_POOL_EXHAUSTED, "too much client requesting provider", "", msg);
if (Boolean.parseBoolean(url.getParameter(DUMP_ENABLE, Boolean.TRUE.toString()))) {
dumpJStack();
}
dispatchThreadPoolExhaustedEvent(msg);
throw new RejectedExecutionException(msg);
}
public void addThreadPoolExhaustedEventListener(ThreadPoolExhaustedListener listener) {
listeners.add(listener);
}
public void removeThreadPoolExhaustedEventListener(ThreadPoolExhaustedListener listener) {
listeners.remove(listener);
}
/**
* dispatch ThreadPoolExhaustedEvent
*
* @param msg
*/
public void dispatchThreadPoolExhaustedEvent(String msg) {
listeners.forEach(listener -> listener.onEvent(new ThreadPoolExhaustedEvent(msg)));
}
private void dumpJStack() {
long now = System.currentTimeMillis();
// dump every 10 minutes
if (now - lastPrintTime < TEN_MINUTES_MILLS) {
return;
}
if (!guard.tryAcquire()) {
return;
}
ExecutorService pool = null;
try {
// To avoid multiple dump, check again
if (System.currentTimeMillis() - lastPrintTime < TEN_MINUTES_MILLS) {
return;
}
pool = Executors.newSingleThreadExecutor();
pool.execute(() -> {
String dumpPath = getDumpPath();
SimpleDateFormat sdf;
String os = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_OS_NAME)
.toLowerCase();
// window system don't support ":" in file name
if (os.contains(OS_WIN_PREFIX)) {
sdf = new SimpleDateFormat(WIN_DATETIME_FORMAT);
} else {
sdf = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
}
String dateStr = sdf.format(new Date());
// try-with-resources
try (FileOutputStream jStackStream =
new FileOutputStream(new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) {
jstack(jStackStream);
} catch (Exception t) {
logger.error(COMMON_UNEXPECTED_CREATE_DUMP, "", "", "dump jStack error", t);
}
});
lastPrintTime = System.currentTimeMillis();
} finally {
guard.release();
// must shut down thread pool ,if not will lead to OOM
if (pool != null) {
pool.shutdown();
}
}
}
protected void jstack(FileOutputStream jStackStream) throws Exception {
JVMUtil.jstack(jStackStream);
}
protected String getDumpPath() {
final String dumpPath = url.getParameter(DUMP_DIRECTORY);
if (StringUtils.isEmpty(dumpPath)) {
return USER_HOME;
}
final File dumpDirectory = new File(dumpPath);
if (!dumpDirectory.exists()) {
if (dumpDirectory.mkdirs()) {
logger.info(format("Dubbo dump directory[%s] created", dumpDirectory.getAbsolutePath()));
} else {
logger.warn(
COMMON_UNEXPECTED_CREATE_DUMP,
"",
"",
format(
"Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]",
dumpDirectory.getAbsolutePath(), USER_HOME));
return USER_HOME;
}
}
return dumpPath;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.limited;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
/**
* Creates a thread pool that creates new threads as needed until limits reaches. This thread pool will not shrink
* automatically.
*/
public class LimitedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS);
int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS);
int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);
BlockingQueue<Runnable> blockingQueue;
if (queues == 0) {
blockingQueue = new SynchronousQueue<>();
} else if (queues < 0) {
blockingQueue = new MemorySafeLinkedBlockingQueue<>();
} else {
blockingQueue = new LinkedBlockingQueue<>(queues);
}
return new ThreadPoolExecutor(
cores,
threads,
Long.MAX_VALUE,
TimeUnit.MILLISECONDS,
blockingQueue,
new NamedInternalThreadFactory(name, true),
new AbortPolicyWithReport(name, url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.cached;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
/**
* This thread pool is self-tuned. Thread will be recycled after idle for one minute, and new thread will be created for
* the upcoming request.
*
* @see java.util.concurrent.Executors#newCachedThreadPool()
*/
public class CachedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS);
int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE);
int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);
int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE);
BlockingQueue<Runnable> blockingQueue;
if (queues == 0) {
blockingQueue = new SynchronousQueue<>();
} else if (queues < 0) {
blockingQueue = new MemorySafeLinkedBlockingQueue<>();
} else {
blockingQueue = new LinkedBlockingQueue<>(queues);
}
return new ThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
blockingQueue,
new NamedInternalThreadFactory(name, true),
new AbortPolicyWithReport(name, url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.fixed;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
/**
* Creates a thread pool that reuses a fixed number of threads
*
* @see java.util.concurrent.Executors#newFixedThreadPool(int)
*/
public class FixedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS);
int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);
BlockingQueue<Runnable> blockingQueue;
if (queues == 0) {
blockingQueue = new SynchronousQueue<>();
} else if (queues < 0) {
blockingQueue = new MemorySafeLinkedBlockingQueue<>();
} else {
blockingQueue = new LinkedBlockingQueue<>(queues);
}
return new ThreadPoolExecutor(
threads,
threads,
0,
TimeUnit.MILLISECONDS,
blockingQueue,
new NamedInternalThreadFactory(name, true),
new AbortPolicyWithReport(name, url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
/**
* EagerThreadPool
* When the core threads are all in busy,
* create new thread instead of putting task into blocking queue.
*/
public class EagerThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS);
int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE);
int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);
int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE);
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues <= 0 ? 1 : queues);
EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedInternalThreadFactory(name, true),
new AbortPolicyWithReport(name, url));
taskQueue.setExecutor(executor);
return executor;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
/**
* TaskQueue in the EagerThreadPoolExecutor
* It offer a task if the executor's submittedTaskCount less than currentPoolThreadSize
* or the currentPoolThreadSize more than executor's maximumPoolSize.
* That can make the executor create new worker
* when the task num is bigger than corePoolSize but less than maximumPoolSize.
*/
public class TaskQueue<R extends Runnable> extends LinkedBlockingQueue<Runnable> {
private static final long serialVersionUID = -2635853580887179627L;
private EagerThreadPoolExecutor executor;
public TaskQueue(int capacity) {
super(capacity);
}
public void setExecutor(EagerThreadPoolExecutor exec) {
executor = exec;
}
@Override
public boolean offer(Runnable runnable) {
if (executor == null) {
throw new RejectedExecutionException("The task queue does not have executor!");
}
int currentPoolThreadSize = executor.getPoolSize();
// have free worker. put task into queue to let the worker deal with task.
if (executor.getActiveCount() < currentPoolThreadSize) {
return super.offer(runnable);
}
// return false to let executor create new worker.
if (currentPoolThreadSize < executor.getMaximumPoolSize()) {
return false;
}
// currentPoolThreadSize >= max
return super.offer(runnable);
}
/**
* retry offer task
*
* @param o task
* @return offer success or not
* @throws RejectedExecutionException if executor is terminated.
*/
public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (executor.isShutdown()) {
throw new RejectedExecutionException("Executor is shutdown!");
}
return super.offer(o, timeout, unit);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class EagerThreadPoolExecutor extends ThreadPoolExecutor {
public EagerThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
TaskQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
public void execute(Runnable command) {
if (command == null) {
throw new NullPointerException();
}
try {
super.execute(command);
} catch (RejectedExecutionException rx) {
// retry to offer the task into queue.
final TaskQueue queue = (TaskQueue) super.getQueue();
try {
if (!queue.retryOffer(command, 0, TimeUnit.MILLISECONDS)) {
throw new RejectedExecutionException("Queue capacity is full.", rx);
}
} catch (InterruptedException x) {
throw new RejectedExecutionException(x);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
@SPI(value = "isolation", scope = ExtensionScope.APPLICATION)
public interface ExecutorRepository {
/**
* Called by both Client and Server. TODO, consider separate these two parts.
* When the Client or Server starts for the first time, generate a new threadpool according to the parameters specified.
*
* @param url
* @return
*/
ExecutorService createExecutorIfAbsent(URL url);
/**
* Be careful,The semantics of this method are getOrDefaultExecutor
*
* @param url
* @return
*/
ExecutorService getExecutor(URL url);
ExecutorService getExecutor(ServiceModel serviceModel, URL url);
/**
* Modify some of the threadpool's properties according to the url, for example, coreSize, maxSize, ...
*
* @param url
* @param executor
*/
void updateThreadpool(URL url, ExecutorService executor);
ScheduledExecutorService getServiceExportExecutor();
/**
* The executor only used in bootstrap currently, we should call this method to release the resource
* after the async export is done.
*/
void shutdownServiceExportExecutor();
ExecutorService getServiceReferExecutor();
/**
* The executor only used in bootstrap currently, we should call this method to release the resource
* after the async refer is done.
*/
void shutdownServiceReferExecutor();
/**
* Destroy all executors that are not in shutdown state
*/
void destroyAll();
/**
* Returns a scheduler from the scheduler list, call this method whenever you need a scheduler for a cron job.
* If your cron cannot burden the possible schedule delay caused by sharing the same scheduler, please consider define a dedicate one.
*
* @deprecated use {@link FrameworkExecutorRepository#nextScheduledExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService nextScheduledExecutor();
/**
* @deprecated use {@link FrameworkExecutorRepository#nextExecutorExecutor()} instead
* @return ExecutorService
*/
@Deprecated
ExecutorService nextExecutorExecutor();
/**
* @deprecated use {@link FrameworkExecutorRepository#getServiceDiscoveryAddressNotificationExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor();
/**
* @deprecated use {@link FrameworkExecutorRepository#getMetadataRetryExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getMetadataRetryExecutor();
/**
* Scheduled executor handle registry notification.
*
* @deprecated use {@link FrameworkExecutorRepository#getRegistryNotificationExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getRegistryNotificationExecutor();
/**
* Get the default shared threadpool.
*
* @deprecated use {@link FrameworkExecutorRepository#getSharedExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ExecutorService getSharedExecutor();
/**
* Get the shared schedule executor
*
* @deprecated use {@link FrameworkExecutorRepository#getSharedScheduledExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getSharedScheduledExecutor();
/**
* @deprecated use {@link FrameworkExecutorRepository#getPoolRouterExecutor()} instead
* @return ExecutorService
*/
@Deprecated
ExecutorService getPoolRouterExecutor();
/**
* Scheduled executor handle connectivity check task
*
* @deprecated use {@link FrameworkExecutorRepository#getConnectivityScheduledExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getConnectivityScheduledExecutor();
/**
* Scheduler used to refresh file based caches from memory to disk.
*
* @deprecated use {@link FrameworkExecutorRepository#getCacheRefreshingScheduledExecutor()} instead
* @return ScheduledExecutorService
*/
@Deprecated
ScheduledExecutorService getCacheRefreshingScheduledExecutor();
/**
* Executor used to run async mapping tasks
*
* @deprecated use {@link FrameworkExecutorRepository#getMappingRefreshingExecutor()} instead
* @return ExecutorService
*/
@Deprecated
ExecutorService getMappingRefreshingExecutor();
ExecutorSupport getExecutorSupport(URL url);
static ExecutorRepository getInstance(ApplicationModel applicationModel) {
ExtensionLoader<ExecutorRepository> extensionLoader =
applicationModel.getExtensionLoader(ExecutorRepository.class);
String mode = getMode(applicationModel);
return StringUtils.isNotEmpty(mode)
? extensionLoader.getExtension(mode)
: extensionLoader.getDefaultExtension();
}
static String getMode(ApplicationModel applicationModel) {
Optional<ApplicationConfig> optional =
applicationModel.getApplicationConfigManager().getApplication();
return optional.map(ApplicationConfig::getExecutorManagementMode).orElse(EXECUTOR_MANAGEMENT_MODE_ISOLATION);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/Ring.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/Ring.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class Ring<T> {
AtomicInteger count = new AtomicInteger();
private final List<T> itemList = new CopyOnWriteArrayList<>();
public void addItem(T t) {
if (t != null) {
itemList.add(t);
}
}
public T pollItem() {
if (itemList.isEmpty()) {
return null;
}
if (itemList.size() == 1) {
return itemList.get(0);
}
if (count.intValue() > Integer.MAX_VALUE - 10000) {
count.set(count.get() % itemList.size());
}
int index = Math.abs(count.getAndIncrement()) % itemList.size();
return itemList.get(index);
}
public T peekItem() {
if (itemList.isEmpty()) {
return null;
}
if (itemList.size() == 1) {
return itemList.get(0);
}
int index = Math.abs(count.get()) % itemList.size();
return itemList.get(index);
}
public List<T> listItems() {
return Collections.unmodifiableList(itemList);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionAccessor;
import org.apache.dubbo.common.extension.ExtensionAccessorAware;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.store.DataStore;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ExecutorUtil;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.rpc.executor.DefaultExecutorSupport;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_EXPORT_THREAD_NUM;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_REFER_THREAD_NUM;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_USE_THREAD_POOL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_EXECUTORS_NO_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN;
/**
* Consider implementing {@code Lifecycle} to enable executors shutdown when the process stops.
*/
public class DefaultExecutorRepository implements ExecutorRepository, ExtensionAccessorAware {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultExecutorRepository.class);
private static final String MAX_KEY = String.valueOf(Integer.MAX_VALUE);
private volatile ScheduledExecutorService serviceExportExecutor;
private volatile ExecutorService serviceReferExecutor;
private final ConcurrentMap<String, ConcurrentMap<String, ExecutorService>> data = new ConcurrentHashMap<>();
private final Object LOCK = new Object();
private ExtensionAccessor extensionAccessor;
private final ApplicationModel applicationModel;
private final FrameworkExecutorRepository frameworkExecutorRepository;
private ExecutorSupport executorSupport;
private final DataStore dataStore;
public DefaultExecutorRepository(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.frameworkExecutorRepository =
applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class);
this.dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension();
}
/**
* Get called when the server or client instance initiating.
*
* @param url
* @return
*/
@Override
public synchronized ExecutorService createExecutorIfAbsent(URL url) {
String executorKey = getExecutorKey(url);
ConcurrentMap<String, ExecutorService> executors =
ConcurrentHashMapUtils.computeIfAbsent(data, executorKey, k -> new ConcurrentHashMap<>());
String executorCacheKey = getExecutorSecondKey(url);
url = setThreadNameIfAbsent(url, executorCacheKey);
URL finalUrl = url;
ExecutorService executor =
ConcurrentHashMapUtils.computeIfAbsent(executors, executorCacheKey, k -> createExecutor(finalUrl));
// If executor has been shut down, create a new one
if (executor.isShutdown() || executor.isTerminated()) {
executors.remove(executorCacheKey);
executor = createExecutor(url);
executors.put(executorCacheKey, executor);
}
dataStore.put(executorKey, executorCacheKey, executor);
return executor;
}
protected URL setThreadNameIfAbsent(URL url, String executorCacheKey) {
if (url.getParameter(THREAD_NAME_KEY) == null) {
String protocol = url.getProtocol();
if (StringUtils.isEmpty(protocol)) {
protocol = DEFAULT_PROTOCOL;
}
url = url.putAttribute(THREAD_NAME_KEY, protocol + "-protocol-" + executorCacheKey);
}
return url;
}
private String getExecutorSecondKey(URL url) {
if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) {
return getConsumerKey(url);
} else {
return getProviderKey(url);
}
}
private String getExecutorSecondKey(ServiceModel serviceModel, URL url) {
if (serviceModel instanceof ConsumerModel) {
return getConsumerKey(serviceModel);
} else {
return getProviderKey((ProviderModel) serviceModel, url);
}
}
private String getConsumerKey(URL url) {
// Consumer's executor is sharing globally, key=Integer.MAX_VALUE
return String.valueOf(Integer.MAX_VALUE);
}
private String getConsumerKey(ServiceModel serviceModel) {
// Consumer's executor is sharing globally, key=Integer.MAX_VALUE
return MAX_KEY;
}
protected String getProviderKey(URL url) {
// Provider's executor is sharing by protocol.
return String.valueOf(url.getPort());
}
protected String getProviderKey(ProviderModel providerModel, URL url) {
// Provider's executor is sharing by protocol.
return String.valueOf(url.getPort());
}
/**
* Return the executor key based on the type (internal or biz) of the current service.
*
* @param url
* @return
*/
private String getExecutorKey(URL url) {
if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) {
return CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY;
}
return EXECUTOR_SERVICE_COMPONENT_KEY;
}
private String getExecutorKey(ServiceModel serviceModel) {
if (serviceModel instanceof ProviderModel) {
return EXECUTOR_SERVICE_COMPONENT_KEY;
} else {
return CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY;
}
}
protected ExecutorService createExecutor(URL url) {
return (ExecutorService) extensionAccessor
.getExtensionLoader(ThreadPool.class)
.getAdaptiveExtension()
.getExecutor(url);
}
@Override
public ExecutorService getExecutor(URL url) {
Map<String, ExecutorService> executors = data.get(getExecutorKey(url));
/*
* It's guaranteed that this method is called after {@link #createExecutorIfAbsent(URL)}, so data should already
* have Executor instances generated and stored.
*/
if (executors == null) {
logger.warn(
COMMON_EXECUTORS_NO_FOUND,
"",
"",
"No available executors, this is not expected, framework should call createExecutorIfAbsent first"
+ "before coming to here.");
return null;
}
// Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol.
String executorCacheKey = getExecutorSecondKey(url);
ExecutorService executor = executors.get(executorCacheKey);
if (executor != null && (executor.isShutdown() || executor.isTerminated())) {
executors.remove(executorCacheKey);
// Does not re-create a shutdown executor, use SHARED_EXECUTOR for downgrade.
executor = null;
logger.info("Executor for " + url + " is shutdown.");
}
if (executor == null) {
return frameworkExecutorRepository.getSharedExecutor();
} else {
return executor;
}
}
@Override
public ExecutorService getExecutor(ServiceModel serviceModel, URL url) {
Map<String, ExecutorService> executors = data.get(getExecutorKey(serviceModel));
/*
* It's guaranteed that this method is called after {@link #createExecutorIfAbsent(URL)}, so data should already
* have Executor instances generated and stored.
*/
if (executors == null) {
logger.warn(
COMMON_EXECUTORS_NO_FOUND,
"",
"",
"No available executors, this is not expected, framework should call createExecutorIfAbsent first"
+ "before coming to here.");
return null;
}
// Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol.
String executorCacheKey = getExecutorSecondKey(serviceModel, url);
ExecutorService executor = executors.get(executorCacheKey);
if (executor != null && (executor.isShutdown() || executor.isTerminated())) {
executors.remove(executorCacheKey);
// Does not re-create a shutdown executor, use SHARED_EXECUTOR for downgrade.
executor = null;
logger.info("Executor for " + url + " is shutdown.");
}
if (executor == null) {
return frameworkExecutorRepository.getSharedExecutor();
} else {
return executor;
}
}
@Override
public void updateThreadpool(URL url, ExecutorService executor) {
try {
if (url.hasParameter(THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
int threads = url.getParameter(THREADS_KEY, 0);
int max = threadPoolExecutor.getMaximumPoolSize();
int core = threadPoolExecutor.getCorePoolSize();
if (threads > 0 && (threads != max || threads != core)) {
if (threads < core) {
threadPoolExecutor.setCorePoolSize(threads);
if (core == max) {
threadPoolExecutor.setMaximumPoolSize(threads);
}
} else {
threadPoolExecutor.setMaximumPoolSize(threads);
if (core == max) {
threadPoolExecutor.setCorePoolSize(threads);
}
}
}
}
} catch (Throwable t) {
logger.error(COMMON_ERROR_USE_THREAD_POOL, "", "", t.getMessage(), t);
}
}
@Override
public ScheduledExecutorService getServiceExportExecutor() {
synchronized (LOCK) {
if (serviceExportExecutor == null) {
int coreSize = getExportThreadNum();
String applicationName = applicationModel.tryGetApplicationName();
applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName;
serviceExportExecutor = Executors.newScheduledThreadPool(
coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-export", true));
}
}
return serviceExportExecutor;
}
@Override
public void shutdownServiceExportExecutor() {
synchronized (LOCK) {
if (serviceExportExecutor != null && !serviceExportExecutor.isShutdown()) {
try {
serviceExportExecutor.shutdown();
} catch (Throwable ignored) {
// ignored
logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored);
}
}
serviceExportExecutor = null;
}
}
@Override
public ExecutorService getServiceReferExecutor() {
synchronized (LOCK) {
if (serviceReferExecutor == null) {
int coreSize = getReferThreadNum();
String applicationName = applicationModel.tryGetApplicationName();
applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName;
serviceReferExecutor = Executors.newFixedThreadPool(
coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-refer", true));
}
}
return serviceReferExecutor;
}
@Override
public void shutdownServiceReferExecutor() {
synchronized (LOCK) {
if (serviceReferExecutor != null && !serviceReferExecutor.isShutdown()) {
try {
serviceReferExecutor.shutdown();
} catch (Throwable ignored) {
logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored);
}
}
serviceReferExecutor = null;
}
}
private Integer getExportThreadNum() {
Integer threadNum = null;
ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel);
for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) {
threadNum = getExportThreadNum(moduleModel);
if (threadNum != null) {
break;
}
}
if (threadNum == null) {
logger.info("Cannot get config `export-thread-num` from module config, using default: "
+ DEFAULT_EXPORT_THREAD_NUM);
return DEFAULT_EXPORT_THREAD_NUM;
}
return threadNum;
}
private Integer getExportThreadNum(ModuleModel moduleModel) {
ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null);
if (moduleConfig == null) {
return null;
}
Integer threadNum = moduleConfig.getExportThreadNum();
if (threadNum == null) {
threadNum = moduleModel.getConfigManager().getProviders().stream()
.map(ProviderConfig::getExportThreadNum)
.filter(k -> k != null && k > 0)
.findAny()
.orElse(null);
}
return threadNum;
}
private Integer getReferThreadNum() {
Integer threadNum = null;
ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel);
for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) {
threadNum = getReferThreadNum(moduleModel);
if (threadNum != null) {
break;
}
}
if (threadNum == null) {
logger.info("Cannot get config `refer-thread-num` from module config, using default: "
+ DEFAULT_REFER_THREAD_NUM);
return DEFAULT_REFER_THREAD_NUM;
}
return threadNum;
}
private Integer getReferThreadNum(ModuleModel moduleModel) {
ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null);
if (moduleConfig == null) {
return null;
}
Integer threadNum = moduleConfig.getReferThreadNum();
if (threadNum == null) {
threadNum = moduleModel.getConfigManager().getConsumers().stream()
.map(ConsumerConfig::getReferThreadNum)
.filter(k -> k != null && k > 0)
.findAny()
.orElse(null);
}
return threadNum;
}
@Override
public void destroyAll() {
logger.info("destroying application executor repository ..");
shutdownServiceExportExecutor();
shutdownServiceReferExecutor();
data.values().forEach(executors -> {
if (executors != null) {
executors.values().forEach(executor -> {
if (executor != null && !executor.isShutdown()) {
try {
ExecutorUtil.shutdownNow(executor, 100);
} catch (Throwable ignored) {
// ignored
logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored);
}
}
});
}
});
data.clear();
}
private void shutdownExecutorService(ExecutorService executorService, String name) {
try {
executorService.shutdownNow();
} catch (Exception e) {
String msg = "shutdown executor service [" + name + "] failed: ";
logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e);
}
}
@Override
public void setExtensionAccessor(ExtensionAccessor extensionAccessor) {
this.extensionAccessor = extensionAccessor;
}
@Override
public ScheduledExecutorService nextScheduledExecutor() {
return frameworkExecutorRepository.nextScheduledExecutor();
}
@Override
public ExecutorService nextExecutorExecutor() {
return frameworkExecutorRepository.nextExecutorExecutor();
}
@Override
public ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor() {
return frameworkExecutorRepository.getServiceDiscoveryAddressNotificationExecutor();
}
@Override
public ScheduledExecutorService getMetadataRetryExecutor() {
return frameworkExecutorRepository.getMetadataRetryExecutor();
}
@Override
public ScheduledExecutorService getRegistryNotificationExecutor() {
return frameworkExecutorRepository.getRegistryNotificationExecutor();
}
@Override
public ExecutorService getSharedExecutor() {
return frameworkExecutorRepository.getSharedExecutor();
}
@Override
public ScheduledExecutorService getSharedScheduledExecutor() {
return frameworkExecutorRepository.getSharedScheduledExecutor();
}
@Override
public ExecutorService getPoolRouterExecutor() {
return frameworkExecutorRepository.getPoolRouterExecutor();
}
@Override
public ScheduledExecutorService getConnectivityScheduledExecutor() {
return frameworkExecutorRepository.getConnectivityScheduledExecutor();
}
@Override
public ScheduledExecutorService getCacheRefreshingScheduledExecutor() {
return frameworkExecutorRepository.getCacheRefreshingScheduledExecutor();
}
@Override
public ExecutorService getMappingRefreshingExecutor() {
return frameworkExecutorRepository.getMappingRefreshingExecutor();
}
@Override
public ExecutorSupport getExecutorSupport(URL url) {
if (executorSupport == null) {
executorSupport = new DefaultExecutorSupport(url);
}
return executorSupport;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/IsolationExecutorRepository.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/IsolationExecutorRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
import org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.concurrent.ExecutorService;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_EXECUTOR;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
/**
* Thread pool isolation between services, that is, a service has its own thread pool and not interfere with each other
*/
public class IsolationExecutorRepository extends DefaultExecutorRepository {
public IsolationExecutorRepository(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
protected URL setThreadNameIfAbsent(URL url, String executorCacheKey) {
if (url.getParameter(THREAD_NAME_KEY) == null) {
url = url.putAttribute(THREAD_NAME_KEY, "isolation-" + executorCacheKey);
}
return url;
}
@Override
protected String getProviderKey(URL url) {
if (url.getAttributes().containsKey(SERVICE_EXECUTOR)) {
return url.getServiceKey();
} else {
return super.getProviderKey(url);
}
}
@Override
protected String getProviderKey(ProviderModel providerModel, URL url) {
if (url.getAttributes().containsKey(SERVICE_EXECUTOR)) {
return providerModel.getServiceKey();
} else {
return super.getProviderKey(url);
}
}
@Override
protected ExecutorService createExecutor(URL url) {
Object executor = url.getAttributes().get(SERVICE_EXECUTOR);
if (executor instanceof ExecutorService) {
return (ExecutorService) executor;
}
return super.createExecutor(url);
}
@Override
public ExecutorSupport getExecutorSupport(URL url) {
return IsolationExecutorSupportFactory.getIsolationExecutorSupport(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN;
public class FrameworkExecutorRepository implements Disposable {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FrameworkExecutorRepository.class);
private final ExecutorService sharedExecutor;
private final ScheduledExecutorService sharedScheduledExecutor;
private final Ring<ScheduledExecutorService> scheduledExecutors = new Ring<>();
private final ScheduledExecutorService connectivityScheduledExecutor;
private final ScheduledExecutorService cacheRefreshingScheduledExecutor;
private final ExecutorService mappingRefreshingExecutor;
public final Ring<ScheduledExecutorService> registryNotificationExecutorRing = new Ring<>();
private final Ring<ScheduledExecutorService> serviceDiscoveryAddressNotificationExecutorRing = new Ring<>();
private final ScheduledExecutorService metadataRetryExecutor;
private final ExecutorService poolRouterExecutor;
private final Ring<ExecutorService> executorServiceRing = new Ring<>();
private final ExecutorService internalServiceExecutor;
public FrameworkExecutorRepository() {
sharedExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-framework-shared-handler", true));
sharedScheduledExecutor =
Executors.newScheduledThreadPool(8, new NamedThreadFactory("Dubbo-framework-shared-scheduler", true));
int availableProcessors = Runtime.getRuntime().availableProcessors();
for (int i = 0; i < availableProcessors; i++) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-framework-scheduler-" + i, true));
scheduledExecutors.addItem(scheduler);
executorServiceRing.addItem(new ThreadPoolExecutor(
1,
1,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new NamedInternalThreadFactory("Dubbo-framework-state-router-loop-" + i, true),
new ThreadPoolExecutor.AbortPolicy()));
}
connectivityScheduledExecutor = Executors.newScheduledThreadPool(
availableProcessors, new NamedThreadFactory("Dubbo-framework-connectivity-scheduler", true));
cacheRefreshingScheduledExecutor = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-framework-cache-refreshing-scheduler", true));
mappingRefreshingExecutor = Executors.newFixedThreadPool(
availableProcessors, new NamedThreadFactory("Dubbo-framework-mapping-refreshing-scheduler", true));
poolRouterExecutor = new ThreadPoolExecutor(
1,
10,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new NamedInternalThreadFactory("Dubbo-framework-state-router-pool-router", true),
new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < availableProcessors; i++) {
ScheduledExecutorService serviceDiscoveryAddressNotificationExecutor =
Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-framework-SD-address-refresh-" + i));
ScheduledExecutorService registryNotificationExecutor = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-framework-registry-notification-" + i));
serviceDiscoveryAddressNotificationExecutorRing.addItem(serviceDiscoveryAddressNotificationExecutor);
registryNotificationExecutorRing.addItem(registryNotificationExecutor);
}
metadataRetryExecutor =
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-metadata-retry"));
internalServiceExecutor = new ThreadPoolExecutor(
0,
100,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new NamedInternalThreadFactory("Dubbo-internal-service", true),
new ThreadPoolExecutor.AbortPolicy());
}
/**
* Returns a scheduler from the scheduler list, call this method whenever you need a scheduler for a cron job.
* If your cron cannot burden the possible schedule delay caused by sharing the same scheduler, please consider define a dedicated one.
*
* @return ScheduledExecutorService
*/
public ScheduledExecutorService nextScheduledExecutor() {
return scheduledExecutors.pollItem();
}
public ExecutorService nextExecutorExecutor() {
return executorServiceRing.pollItem();
}
/**
* Scheduled executor handle registry notification.
*
* @return ScheduledExecutorService
*/
public ScheduledExecutorService getRegistryNotificationExecutor() {
return registryNotificationExecutorRing.pollItem();
}
public ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor() {
return serviceDiscoveryAddressNotificationExecutorRing.pollItem();
}
public ScheduledExecutorService getMetadataRetryExecutor() {
return metadataRetryExecutor;
}
public ExecutorService getInternalServiceExecutor() {
return internalServiceExecutor;
}
/**
* Get the default shared thread pool.
*
* @return ExecutorService
*/
public ExecutorService getSharedExecutor() {
return sharedExecutor;
}
/**
* Get the shared schedule executor
*
* @return ScheduledExecutorService
*/
public ScheduledExecutorService getSharedScheduledExecutor() {
return sharedScheduledExecutor;
}
public ExecutorService getPoolRouterExecutor() {
return poolRouterExecutor;
}
/**
* Scheduled executor handle connectivity check task
*
* @return ScheduledExecutorService
*/
public ScheduledExecutorService getConnectivityScheduledExecutor() {
return connectivityScheduledExecutor;
}
/**
* Scheduler used to refresh file based caches from memory to disk.
*
* @return ScheduledExecutorService
*/
public ScheduledExecutorService getCacheRefreshingScheduledExecutor() {
return cacheRefreshingScheduledExecutor;
}
/**
* Executor used to run async mapping tasks
*
* @return ExecutorService
*/
public ExecutorService getMappingRefreshingExecutor() {
return mappingRefreshingExecutor;
}
@Override
public void destroy() {
logger.info("destroying framework executor repository ..");
shutdownExecutorService(poolRouterExecutor, "poolRouterExecutor");
shutdownExecutorService(metadataRetryExecutor, "metadataRetryExecutor");
shutdownExecutorService(internalServiceExecutor, "internalServiceExecutor");
// scheduledExecutors
shutdownExecutorServices(scheduledExecutors.listItems(), "scheduledExecutors");
// executorServiceRing
shutdownExecutorServices(executorServiceRing.listItems(), "executorServiceRing");
// connectivityScheduledExecutor
shutdownExecutorService(connectivityScheduledExecutor, "connectivityScheduledExecutor");
shutdownExecutorService(cacheRefreshingScheduledExecutor, "cacheRefreshingScheduledExecutor");
// shutdown share executor
shutdownExecutorService(sharedExecutor, "sharedExecutor");
shutdownExecutorService(sharedScheduledExecutor, "sharedScheduledExecutor");
// serviceDiscoveryAddressNotificationExecutorRing
shutdownExecutorServices(
serviceDiscoveryAddressNotificationExecutorRing.listItems(),
"serviceDiscoveryAddressNotificationExecutorRing");
// registryNotificationExecutorRing
shutdownExecutorServices(registryNotificationExecutorRing.listItems(), "registryNotificationExecutorRing");
// mappingRefreshingExecutor
shutdownExecutorService(mappingRefreshingExecutor, "mappingRefreshingExecutor");
}
private void shutdownExecutorServices(List<? extends ExecutorService> executorServices, String msg) {
for (ExecutorService executorService : executorServices) {
shutdownExecutorService(executorService, msg);
}
}
private void shutdownExecutorService(ExecutorService executorService, String name) {
try {
executorService.shutdownNow();
if (!executorService.awaitTermination(
ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) {
logger.warn(
COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN,
"",
"",
"Wait global executor service terminated timeout.");
}
} catch (Exception e) {
String msg = "shutdown executor service [" + name + "] failed: ";
logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class ScheduledCompletableFuture {
public static <T> CompletableFuture<T> schedule(
ScheduledExecutorService executor, Supplier<T> task, long delay, TimeUnit unit) {
CompletableFuture<T> completableFuture = new CompletableFuture<>();
executor.schedule(
() -> {
try {
return completableFuture.complete(task.get());
} catch (Throwable t) {
return completableFuture.completeExceptionally(t);
}
},
delay,
unit);
return completableFuture;
}
public static <T> CompletableFuture<T> submit(ScheduledExecutorService executor, Supplier<T> task) {
CompletableFuture<T> completableFuture = new CompletableFuture<>();
executor.submit(() -> {
try {
return completableFuture.complete(task.get());
} catch (Throwable t) {
return completableFuture.completeExceptionally(t);
}
});
return completableFuture;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedListener.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.event;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ThreadPoolExhaustedListener {
/**
* Notify when the thread pool is exhausted.
* {@link org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport}
*/
void onEvent(ThreadPoolExhaustedEvent event);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEvent.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.event;
/**
* An Event when the Dubbo thread pool is exhausted.
*/
public class ThreadPoolExhaustedEvent {
final String msg;
public ThreadPoolExhaustedEvent(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java | dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java | /*
* Copyright 2014 The gRPC Authors
*
* 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 org.apache.dubbo.common.threadpool.serial;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK;
import static org.apache.dubbo.common.utils.ExecutorUtil.isShutdown;
/**
* Executor ensuring that all {@link Runnable} tasks submitted are executed in order
* using the provided {@link Executor}, and serially such that no two will ever be
* running at the same time.
*/
public final class SerializingExecutor implements Executor, Runnable {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(SerializingExecutor.class);
/**
* Use false to stop and true to run
*/
private final AtomicBoolean atomicBoolean = new AtomicBoolean();
private final Executor executor;
private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<>();
/**
* Creates a SerializingExecutor, running tasks using {@code executor}.
*
* @param executor Executor in which tasks should be run. Must not be null.
*/
public SerializingExecutor(Executor executor) {
this.executor = executor;
}
/**
* Runs the given runnable strictly after all Runnables that were submitted
* before it, and using the {@code executor} passed to the constructor. .
*/
@Override
public void execute(Runnable r) {
runQueue.add(r);
schedule(r);
}
private void schedule(Runnable removable) {
if (atomicBoolean.compareAndSet(false, true)) {
boolean success = false;
try {
if (!isShutdown(executor)) {
executor.execute(this);
success = true;
}
} catch (RejectedExecutionException e) {
if (!isShutdown(executor)) {
// ignore exception if the executor is shutdown
throw e;
}
} finally {
// It is possible that at this point that there are still tasks in
// the queue, it would be nice to keep trying but the error may not
// be recoverable. So we update our state and propagate so that if
// our caller deems it recoverable we won't be stuck.
if (!success) {
if (removable != null) {
// This case can only be reached if 'this' was not currently running, and we failed to
// reschedule. The item should still be in the queue for removal.
// ConcurrentLinkedQueue claims that null elements are not allowed, but seems to not
// throw if the item to remove is null. If removable is present in the queue twice,
// the wrong one may be removed. It doesn't seem possible for this case to exist today.
// This is important to run in case of RejectedExecutionException, so that future calls
// to execute don't succeed and accidentally run a previous runnable.
runQueue.remove(removable);
}
atomicBoolean.set(false);
}
}
}
}
@Override
public void run() {
Runnable r;
try {
while ((r = runQueue.poll()) != null) {
InternalThreadLocalMap internalThreadLocalMap = InternalThreadLocalMap.getAndRemove();
try {
r.run();
} catch (RuntimeException e) {
LOGGER.error(COMMON_ERROR_RUN_THREAD_TASK, "", "", "Exception while executing runnable " + r, e);
} finally {
InternalThreadLocalMap.set(internalThreadLocalMap);
}
}
} finally {
atomicBoolean.set(false);
}
if (!runQueue.isEmpty()) {
// we didn't enqueue anything but someone else did.
schedule(null);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status;
public class Status {
private final Level level;
private final String message;
private final String description;
public Status(Level level) {
this(level, null, null);
}
public Status(Level level, String message) {
this(level, message, null);
}
public Status(Level level, String message, String description) {
this.level = level;
this.message = message;
this.description = description;
}
public Level getLevel() {
return level;
}
public String getMessage() {
return message;
}
public String getDescription() {
return description;
}
/**
* Level
*/
public enum Level {
/**
* OK
*/
OK,
/**
* WARN
*/
WARN,
/**
* ERROR
*/
ERROR,
/**
* UNKNOWN
*/
UNKNOWN
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.APPLICATION)
public interface StatusChecker {
/**
* check status
*
* @return status
*/
Status check();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
/**
* MemoryStatus
*/
@Activate
public class MemoryStatusChecker implements StatusChecker {
@Override
public Status check() {
Runtime runtime = Runtime.getRuntime();
long freeMemory = runtime.freeMemory();
long totalMemory = runtime.totalMemory();
long maxMemory = runtime.maxMemory();
boolean ok = (maxMemory - (totalMemory - freeMemory) > 2 * 1024 * 1024); // Alarm when spare memory < 2M
String msg = "max:" + (maxMemory / 1024 / 1024) + "M,total:" + (totalMemory / 1024 / 1024) + "M,used:"
+ ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M,free:" + (freeMemory / 1024 / 1024)
+ "M";
return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.system.OperatingSystemBeanManager;
/**
* Load Status
*/
@Activate
public class LoadStatusChecker implements StatusChecker {
@Override
public Status check() {
double load = OperatingSystemBeanManager.getOperatingSystemBean().getSystemLoadAverage();
if (load == -1) {
load = OperatingSystemBeanManager.getSystemCpuUsage();
}
int cpu = OperatingSystemBeanManager.getOperatingSystemBean().getAvailableProcessors();
Status.Level level;
if (load < 0) {
level = Status.Level.UNKNOWN;
} else if (load < cpu) {
level = Status.Level.OK;
} else {
level = Status.Level.WARN;
}
String message = (load < 0 ? "" : "load:" + load + ",") + "cpu:" + cpu;
return new Status(level, message);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.Status.Level;
import java.util.Map;
/**
* StatusManager
*/
public class StatusUtils {
public static Status getSummaryStatus(Map<String, Status> statuses) {
Level level = Level.OK;
StringBuilder msg = new StringBuilder();
for (Map.Entry<String, Status> entry : statuses.entrySet()) {
String key = entry.getKey();
Status status = entry.getValue();
Level l = status.getLevel();
if (Level.ERROR.equals(l)) {
level = Level.ERROR;
if (msg.length() > 0) {
msg.append(',');
}
msg.append(key);
} else if (Level.WARN.equals(l)) {
if (!Level.ERROR.equals(level)) {
level = Level.WARN;
}
if (msg.length() > 0) {
msg.append(',');
}
msg.append(key);
}
}
return new Status(level, msg.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.reporter;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ScopeModelAware;
@SPI(scope = ExtensionScope.APPLICATION)
public interface FrameworkStatusReporter extends ScopeModelAware {
void report(String type, Object obj);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java | dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.reporter;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.HashMap;
import java.util.Set;
public class FrameworkStatusReportService implements ScopeModelAware {
private static final Logger logger = LoggerFactory.getLogger(FrameworkStatusReporter.class);
public static final String REGISTRATION_STATUS = "registration";
public static final String ADDRESS_CONSUMPTION_STATUS = "consumption";
public static final String MIGRATION_STEP_STATUS = "migrationStepStatus";
private ApplicationModel applicationModel;
private Set<FrameworkStatusReporter> reporters;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
reporters = applicationModel
.getExtensionLoader(FrameworkStatusReporter.class)
.getSupportedExtensionInstances();
}
public void reportRegistrationStatus(Object obj) {
doReport(REGISTRATION_STATUS, obj);
}
public void reportConsumptionStatus(Object obj) {
doReport(ADDRESS_CONSUMPTION_STATUS, obj);
}
public void reportMigrationStepStatus(Object obj) {
doReport(MIGRATION_STEP_STATUS, obj);
}
public boolean hasReporter() {
return reporters.size() > 0;
}
private void doReport(String type, Object obj) {
// TODO, report asynchronously
try {
if (CollectionUtils.isNotEmpty(reporters)) {
for (FrameworkStatusReporter reporter : reporters) {
reporter.report(type, obj);
}
}
} catch (Exception e) {
logger.info("Report " + type + " status failed because of " + e.getMessage());
}
}
public String createRegistrationReport(String status) {
HashMap<String, String> registration = new HashMap<>();
registration.put("application", applicationModel.getApplicationName());
registration.put("status", status);
return JsonUtils.toJson(registration);
}
public String createConsumptionReport(String interfaceName, String version, String group, String status) {
HashMap<String, String> migrationStatus = new HashMap<>();
migrationStatus.put("type", "consumption");
migrationStatus.put("application", applicationModel.getApplicationName());
migrationStatus.put("service", interfaceName);
migrationStatus.put("version", version);
migrationStatus.put("group", group);
migrationStatus.put("status", status);
return JsonUtils.toJson(migrationStatus);
}
public String createMigrationStepReport(
String interfaceName, String version, String group, String originStep, String newStep, String success) {
HashMap<String, String> migrationStatus = new HashMap<>();
migrationStatus.put("type", "migrationStepStatus");
migrationStatus.put("application", applicationModel.getApplicationName());
migrationStatus.put("service", interfaceName);
migrationStatus.put("version", version);
migrationStatus.put("group", group);
migrationStatus.put("originStep", originStep);
migrationStatus.put("newStep", newStep);
migrationStatus.put("success", success);
return JsonUtils.toJson(migrationStatus);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
/**
* UnsafeByteArrayOutputStream.
*/
public class UnsafeByteArrayOutputStream extends OutputStream {
protected byte[] mBuffer;
protected int mCount;
public UnsafeByteArrayOutputStream() {
this(32);
}
public UnsafeByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: " + size);
}
mBuffer = new byte[size];
}
@Override
public void write(int b) {
int newCount = mCount + 1;
if (newCount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newCount));
}
mBuffer[mCount] = (byte) b;
mCount = newCount;
}
@Override
public void write(byte[] b, int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return;
}
int newCount = mCount + len;
if (newCount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newCount));
}
System.arraycopy(b, off, mBuffer, mCount, len);
mCount = newCount;
}
public int size() {
return mCount;
}
public void reset() {
mCount = 0;
}
public byte[] toByteArray() {
return Bytes.copyOf(mBuffer, mCount);
}
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(mBuffer, 0, mCount);
}
public void writeTo(OutputStream out) throws IOException {
out.write(mBuffer, 0, mCount);
}
@Override
public String toString() {
return new String(mBuffer, 0, mCount);
}
public String toString(String charset) throws UnsupportedEncodingException {
return new String(mBuffer, 0, mCount, charset);
}
@Override
public void close() throws IOException {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.InputStream;
/**
* UnsafeByteArrayInputStream.
*/
public class UnsafeByteArrayInputStream extends InputStream {
protected byte[] mData;
protected int mPosition, mLimit, mMark = 0;
public UnsafeByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public UnsafeByteArrayInputStream(byte[] buf, int offset) {
this(buf, offset, buf.length - offset);
}
public UnsafeByteArrayInputStream(byte[] buf, int offset, int length) {
mData = buf;
mPosition = mMark = offset;
mLimit = Math.min(offset + length, buf.length);
}
@Override
public int read() {
return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1;
}
@Override
public int read(byte[] b, int off, int len) {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
System.arraycopy(mData, mPosition, b, off, len);
mPosition += len;
return len;
}
@Override
public long skip(long len) {
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
mPosition += len;
return len;
}
@Override
public int available() {
return mLimit - mPosition;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit) {
mMark = mPosition;
}
@Override
public void reset() {
mPosition = mMark;
}
@Override
public void close() throws IOException {}
public int position() {
return mPosition;
}
public void position(int newPosition) {
mPosition = newPosition;
}
public int size() {
return mData == null ? 0 : mData.length;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.Reader;
/**
* Thread-unsafe StringReader.
*/
public class UnsafeStringReader extends Reader {
private String mString;
private int mPosition, mLimit, mMark;
public UnsafeStringReader(String str) {
mString = str;
mLimit = str.length();
mPosition = mMark = 0;
}
@Override
public int read() throws IOException {
ensureOpen();
if (mPosition >= mLimit) {
return -1;
}
return mString.charAt(mPosition++);
}
@Override
public int read(char[] cs, int off, int len) throws IOException {
ensureOpen();
if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
if (mPosition >= mLimit) {
return -1;
}
int n = Math.min(mLimit - mPosition, len);
mString.getChars(mPosition, mPosition + n, cs, off);
mPosition += n;
return n;
}
@Override
public long skip(long ns) throws IOException {
ensureOpen();
if (mPosition >= mLimit) {
return 0;
}
long n = Math.min(mLimit - mPosition, ns);
n = Math.max(-mPosition, n);
mPosition += n;
return n;
}
@Override
public boolean ready() throws IOException {
ensureOpen();
return true;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
ensureOpen();
mMark = mPosition;
}
@Override
public void reset() throws IOException {
ensureOpen();
mPosition = mMark;
}
@Override
public void close() throws IOException {
mString = null;
}
private void ensureOpen() throws IOException {
if (mString == null) {
throw new IOException("Stream closed");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.Writer;
/**
* Thread-unsafe StringWriter.
*/
public class UnsafeStringWriter extends Writer {
private final StringBuilder mBuffer;
public UnsafeStringWriter() {
lock = mBuffer = new StringBuilder();
}
public UnsafeStringWriter(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative buffer size");
}
lock = mBuffer = new StringBuilder(size);
}
@Override
public void write(int c) {
mBuffer.append((char) c);
}
@Override
public void write(char[] cs) throws IOException {
mBuffer.append(cs, 0, cs.length);
}
@Override
public void write(char[] cs, int off, int len) throws IOException {
if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len > 0) {
mBuffer.append(cs, off, len);
}
}
@Override
public void write(String str) {
mBuffer.append(str);
}
@Override
public void write(String str, int off, int len) {
mBuffer.append(str, off, off + len);
}
@Override
public Writer append(CharSequence csq) {
if (csq == null) {
write("null");
} else {
write(csq.toString());
}
return this;
}
@Override
public Writer append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}
@Override
public Writer append(char c) {
mBuffer.append(c);
return this;
}
@Override
public void close() {}
@Override
public void flush() {}
@Override
public String toString() {
return mBuffer.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import org.apache.dubbo.common.utils.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/**
* CodecUtils.
*/
public class Bytes {
private static final String C64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64.
private static final char[]
BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'},
BASE64 = C64.toCharArray();
private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff;
private static final Map<Integer, byte[]> DECODE_TABLE_MAP = new ConcurrentHashMap<>();
private static final ThreadLocal<MessageDigest> MD = new ThreadLocal<>();
private Bytes() {}
/**
* byte array copy.
*
* @param src src.
* @param length new length.
* @return new byte array.
*/
public static byte[] copyOf(byte[] src, int length) {
byte[] dest = new byte[length];
System.arraycopy(src, 0, dest, 0, Math.min(src.length, length));
return dest;
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] short2bytes(short v) {
byte[] ret = {0, 0};
short2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void short2bytes(short v, byte[] b) {
short2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void short2bytes(short v, byte[] b, int off) {
b[off + 1] = (byte) v;
b[off + 0] = (byte) (v >>> 8);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] int2bytes(int v) {
byte[] ret = {0, 0, 0, 0};
int2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void int2bytes(int v, byte[] b) {
int2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void int2bytes(int v, byte[] b, int off) {
b[off + 3] = (byte) v;
b[off + 2] = (byte) (v >>> 8);
b[off + 1] = (byte) (v >>> 16);
b[off + 0] = (byte) (v >>> 24);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] float2bytes(float v) {
byte[] ret = {0, 0, 0, 0};
float2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void float2bytes(float v, byte[] b) {
float2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void float2bytes(float v, byte[] b, int off) {
int i = Float.floatToIntBits(v);
b[off + 3] = (byte) i;
b[off + 2] = (byte) (i >>> 8);
b[off + 1] = (byte) (i >>> 16);
b[off + 0] = (byte) (i >>> 24);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] long2bytes(long v) {
byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0};
long2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void long2bytes(long v, byte[] b) {
long2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void long2bytes(long v, byte[] b, int off) {
b[off + 7] = (byte) v;
b[off + 6] = (byte) (v >>> 8);
b[off + 5] = (byte) (v >>> 16);
b[off + 4] = (byte) (v >>> 24);
b[off + 3] = (byte) (v >>> 32);
b[off + 2] = (byte) (v >>> 40);
b[off + 1] = (byte) (v >>> 48);
b[off + 0] = (byte) (v >>> 56);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] double2bytes(double v) {
byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0};
double2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void double2bytes(double v, byte[] b) {
double2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void double2bytes(double v, byte[] b, int off) {
long j = Double.doubleToLongBits(v);
b[off + 7] = (byte) j;
b[off + 6] = (byte) (j >>> 8);
b[off + 5] = (byte) (j >>> 16);
b[off + 4] = (byte) (j >>> 24);
b[off + 3] = (byte) (j >>> 32);
b[off + 2] = (byte) (j >>> 40);
b[off + 1] = (byte) (j >>> 48);
b[off + 0] = (byte) (j >>> 56);
}
/**
* to short.
*
* @param b byte array.
* @return short.
*/
public static short bytes2short(byte[] b) {
return bytes2short(b, 0);
}
/**
* to short.
*
* @param b byte array.
* @param off offset.
* @return short.
*/
public static short bytes2short(byte[] b, int off) {
return (short) (((b[off + 1] & 0xFF) << 0) + ((b[off + 0]) << 8));
}
/**
* to int.
*
* @param b byte array.
* @return int.
*/
public static int bytes2int(byte[] b) {
return bytes2int(b, 0);
}
/**
* to int.
*
* @param b byte array.
* @param off offset.
* @return int.
*/
public static int bytes2int(byte[] b, int off) {
return ((b[off + 3] & 0xFF) << 0)
+ ((b[off + 2] & 0xFF) << 8)
+ ((b[off + 1] & 0xFF) << 16)
+ ((b[off + 0]) << 24);
}
/**
* to int.
*
* @param b byte array.
* @return int.
*/
public static float bytes2float(byte[] b) {
return bytes2float(b, 0);
}
/**
* to int.
*
* @param b byte array.
* @param off offset.
* @return int.
*/
public static float bytes2float(byte[] b, int off) {
int i = ((b[off + 3] & 0xFF) << 0)
+ ((b[off + 2] & 0xFF) << 8)
+ ((b[off + 1] & 0xFF) << 16)
+ ((b[off + 0]) << 24);
return Float.intBitsToFloat(i);
}
/**
* to long.
*
* @param b byte array.
* @return long.
*/
public static long bytes2long(byte[] b) {
return bytes2long(b, 0);
}
/**
* to long.
*
* @param b byte array.
* @param off offset.
* @return long.
*/
public static long bytes2long(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) << 0)
+ ((b[off + 6] & 0xFFL) << 8)
+ ((b[off + 5] & 0xFFL) << 16)
+ ((b[off + 4] & 0xFFL) << 24)
+ ((b[off + 3] & 0xFFL) << 32)
+ ((b[off + 2] & 0xFFL) << 40)
+ ((b[off + 1] & 0xFFL) << 48)
+ (((long) b[off + 0]) << 56);
}
/**
* to long.
*
* @param b byte array.
* @return double.
*/
public static double bytes2double(byte[] b) {
return bytes2double(b, 0);
}
/**
* to long.
*
* @param b byte array.
* @param off offset.
* @return double.
*/
public static double bytes2double(byte[] b, int off) {
long j = ((b[off + 7] & 0xFFL) << 0)
+ ((b[off + 6] & 0xFFL) << 8)
+ ((b[off + 5] & 0xFFL) << 16)
+ ((b[off + 4] & 0xFFL) << 24)
+ ((b[off + 3] & 0xFFL) << 32)
+ ((b[off + 2] & 0xFFL) << 40)
+ ((b[off + 1] & 0xFFL) << 48)
+ (((long) b[off + 0]) << 56);
return Double.longBitsToDouble(j);
}
/**
* to hex string.
*
* @param bs byte array.
* @return hex string.
*/
public static String bytes2hex(byte[] bs) {
return bytes2hex(bs, 0, bs.length);
}
/**
* to hex string.
*
* @param bs byte array.
* @param off offset.
* @param len length.
* @return hex string.
*/
public static String bytes2hex(byte[] bs, int off, int len) {
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len);
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length.");
}
byte b;
int r = off, w = 0;
char[] cs = new char[len * 2];
for (int i = 0; i < len; i++) {
b = bs[r++];
cs[w++] = BASE16[b >> 4 & MASK4];
cs[w++] = BASE16[b & MASK4];
}
return new String(cs);
}
/**
* from hex string.
*
* @param str hex string.
* @return byte array.
*/
public static byte[] hex2bytes(String str) {
return hex2bytes(str, 0, str.length());
}
/**
* from hex string.
*
* @param str hex string.
* @param off offset.
* @param len length.
* @return byte array.
*/
public static byte[] hex2bytes(final String str, final int off, int len) {
if ((len & 1) == 1) {
throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1.");
}
if (off < 0) {
throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len);
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length.");
}
int num = len / 2, r = off, w = 0;
byte[] b = new byte[num];
for (int i = 0; i < num; i++) {
b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++)));
}
return b;
}
/**
* to base64 string.
*
* @param b byte array.
* @return base64 string.
*/
public static String bytes2base64(byte[] b) {
return bytes2base64(b, 0, b.length, BASE64);
}
/**
* to base64 string.
*
* @param b byte array.
* @return base64 string.
*/
public static String bytes2base64(byte[] b, int offset, int length) {
return bytes2base64(b, offset, length, BASE64);
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code string(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, String code) {
return bytes2base64(b, 0, b.length, code);
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code string(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, int offset, int length, String code) {
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
return bytes2base64(b, offset, length, code.toCharArray());
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, char[] code) {
return bytes2base64(b, 0, b.length, code);
}
/**
* to base64 string.
*
* @param bs byte array.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) {
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len);
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length.");
}
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
boolean pad = code.length > 64; // has pad char.
int num = len / 3, rem = len % 3, r = off, w = 0;
char[] cs = new char[num * 4 + (rem == 0 ? 0 : pad ? 4 : rem + 1)];
for (int i = 0; i < num; i++) {
int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8, b3 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)];
cs[w++] = code[(b2 << 2) & MASK6 | (b3 >> 6)];
cs[w++] = code[b3 & MASK6];
}
if (rem == 1) {
int b1 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6];
if (pad) {
cs[w++] = code[64];
cs[w++] = code[64];
}
} else if (rem == 2) {
int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)];
cs[w++] = code[(b2 << 2) & MASK6];
if (pad) {
cs[w++] = code[64];
}
}
return new String(cs);
}
/**
* from base64 string.
*
* @param str base64 string.
* @return byte array.
*/
public static byte[] base642bytes(String str) {
return base642bytes(str, 0, str.length());
}
/**
* from base64 string.
*
* @param str base64 string.
* @param offset offset.
* @param length length.
* @return byte array.
*/
public static byte[] base642bytes(String str, int offset, int length) {
return base642bytes(str, offset, length, C64);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(String str, String code) {
return base642bytes(str, 0, str.length(), code);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final String code) {
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
}
if (len == 0) {
return new byte[0];
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length() > 64) {
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code.charAt(64);
if (str.charAt(off + len - 2) == pc) {
size -= 2;
--num;
rem = 2;
} else if (str.charAt(off + len - 1) == pc) {
size--;
--num;
rem = 3;
}
} else {
if (rem == 2) {
size++;
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
byte[] b = new byte[size], t = decodeTable(code);
for (int i = 0; i < num; i++) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)];
int c3 = t[str.charAt(r++)], c4 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
b[w++] = (byte) ((c3 << 6) | c4);
}
if (rem == 2) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
} else if (rem == 3) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)], c3 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
}
return b;
}
/**
* from base64 string.
*
* @param str base64 string.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(String str, char[] code) {
return base642bytes(str, 0, str.length(), code);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) {
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
}
if (len == 0) {
return new byte[0];
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length > 64) {
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code[64];
if (str.charAt(off + len - 2) == pc) {
size -= 2;
--num;
rem = 2;
} else if (str.charAt(off + len - 1) == pc) {
size--;
--num;
rem = 3;
}
} else {
if (rem == 2) {
size++;
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
byte[] b = new byte[size];
for (int i = 0; i < num; i++) {
int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++));
int c3 = indexOf(code, str.charAt(r++)), c4 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
b[w++] = (byte) ((c3 << 6) | c4);
}
if (rem == 2) {
int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
} else if (rem == 3) {
int c1 = indexOf(code, str.charAt(r++)),
c2 = indexOf(code, str.charAt(r++)),
c3 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
}
return b;
}
/**
* zip.
*
* @param bytes source.
* @return compressed byte array.
* @throws IOException
*/
public static byte[] zip(byte[] bytes) throws IOException {
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
OutputStream os = new DeflaterOutputStream(bos);
try {
os.write(bytes);
} finally {
os.close();
bos.close();
}
return bos.toByteArray();
}
/**
* unzip.
*
* @param bytes compressed byte array.
* @return byte uncompressed array.
* @throws IOException
*/
public static byte[] unzip(byte[] bytes) throws IOException {
UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
InputStream is = new InflaterInputStream(bis);
try {
IOUtils.write(is, bos);
return bos.toByteArray();
} finally {
is.close();
bis.close();
bos.close();
}
}
/**
* get md5.
*
* @param str input string.
* @return MD5 byte array.
*/
public static byte[] getMD5(String str) {
return getMD5(str.getBytes(StandardCharsets.UTF_8));
}
/**
* get md5.
*
* @param source byte array source.
* @return MD5 byte array.
*/
public static byte[] getMD5(byte[] source) {
MessageDigest md = getMessageDigest();
return md.digest(source);
}
/**
* get md5.
*
* @param file file source.
* @return MD5 byte array.
*/
public static byte[] getMD5(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
return getMD5(is);
} finally {
is.close();
}
}
/**
* get md5.
*
* @param is input stream.
* @return MD5 byte array.
*/
public static byte[] getMD5(InputStream is) throws IOException {
return getMD5(is, 1024 * 8);
}
private static byte hex(char c) {
if (c <= '9') {
return (byte) (c - '0');
}
if (c >= 'a' && c <= 'f') {
return (byte) (c - 'a' + 10);
}
if (c >= 'A' && c <= 'F') {
return (byte) (c - 'A' + 10);
}
throw new IllegalArgumentException("hex string format error [" + c + "].");
}
private static int indexOf(char[] cs, char c) {
for (int i = 0, len = cs.length; i < len; i++) {
if (cs[i] == c) {
return i;
}
}
return -1;
}
private static byte[] decodeTable(String code) {
int hash = code.hashCode();
byte[] ret = DECODE_TABLE_MAP.get(hash);
if (ret == null) {
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
// create new decode table.
ret = new byte[128];
for (int i = 0; i < 128; i++) // init table.
{
ret[i] = -1;
}
for (int i = 0; i < 64; i++) {
ret[code.charAt(i)] = (byte) i;
}
DECODE_TABLE_MAP.put(hash, ret);
}
return ret;
}
private static byte[] getMD5(InputStream is, int bs) throws IOException {
MessageDigest md = getMessageDigest();
byte[] buf = new byte[bs];
while (is.available() > 0) {
int read, total = 0;
do {
if ((read = is.read(buf, total, bs - total)) <= 0) {
break;
}
total += read;
} while (total < bs);
md.update(buf);
}
return md.digest();
}
private static MessageDigest getMessageDigest() {
MessageDigest ret = MD.get();
if (ret == null) {
try {
ret = MessageDigest.getInstance("MD5");
MD.set(ret);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
return ret;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Stream utils.
*/
public final class StreamUtils {
public static final ByteArrayInputStream EMPTY = new ByteArrayInputStream(new byte[0]);
private StreamUtils() {}
public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException {
return new InputStream() {
private int mPosition = 0;
private int mMark = 0;
private final int mLimit = Math.min(limit, is.available());
@Override
public int read() throws IOException {
if (mPosition < mLimit) {
mPosition++;
return is.read();
}
return -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.read(b, off, len);
mPosition += len;
return len;
}
@Override
public long skip(long len) throws IOException {
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.skip(len);
mPosition += len;
return len;
}
@Override
public int available() {
return mLimit - mPosition;
}
@Override
public boolean markSupported() {
return is.markSupported();
}
@Override
public synchronized void mark(int readlimit) {
is.mark(readlimit);
mMark = mPosition;
}
@Override
public synchronized void reset() throws IOException {
is.reset();
mPosition = mMark;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) {
if (is.markSupported()) {
return is;
}
return new InputStream() {
byte[] mMarkBuffer;
boolean mInMarked = false;
boolean mInReset = false;
boolean mDry = false;
private int mPosition = 0;
private int mCount = 0;
@Override
public int read() throws IOException {
if (!mInMarked) {
return is.read();
} else {
if (mPosition < mCount) {
byte b = mMarkBuffer[mPosition++];
return b & 0xFF;
}
if (!mInReset) {
if (mDry) {
return -1;
}
if (null == mMarkBuffer) {
mMarkBuffer = new byte[markBufferSize];
}
if (mPosition >= markBufferSize) {
throw new IOException("Mark buffer is full!");
}
int read = is.read();
if (-1 == read) {
mDry = true;
return -1;
}
mMarkBuffer[mPosition++] = (byte) read;
mCount++;
return read;
} else {
// mark buffer is used, exit mark status!
mInMarked = false;
mInReset = false;
mPosition = 0;
mCount = 0;
return is.read();
}
}
}
/**
* NOTE: the <code>readlimit</code> argument for this class
* has no meaning.
*/
@Override
public synchronized void mark(int readlimit) {
mInMarked = true;
mInReset = false;
// mark buffer is not empty
int count = mCount - mPosition;
if (count > 0) {
System.arraycopy(mMarkBuffer, mPosition, mMarkBuffer, 0, count);
mCount = count;
mPosition = 0;
}
}
@Override
public synchronized void reset() throws IOException {
if (!mInMarked) {
throw new IOException("should mark before reset!");
}
mInReset = true;
mPosition = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int available() throws IOException {
int available = is.available();
if (mInMarked && mInReset) {
available += mCount - mPosition;
}
return available;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is) {
return markSupportedInputStream(is, 1024);
}
public static void skipUnusedStream(InputStream is) throws IOException {
if (is.available() > 0) {
is.skip(is.available());
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
if (in.getClass() == ByteArrayInputStream.class) {
copy((ByteArrayInputStream) in, out);
return;
}
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
public static void copy(ByteArrayInputStream in, OutputStream out) throws IOException {
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer, 0, len);
out.write(buffer, 0, len);
}
public static byte[] readBytes(InputStream in) throws IOException {
if (in.getClass() == ByteArrayInputStream.class) {
return readBytes((ByteArrayInputStream) in);
}
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
}
public static byte[] readBytes(ByteArrayInputStream in) throws IOException {
int len = in.available();
byte[] bytes = new byte[len];
in.read(bytes, 0, len);
return bytes;
}
public static String toString(InputStream in) throws IOException {
return new String(readBytes(in), StandardCharsets.UTF_8);
}
public static String toString(InputStream in, Charset charset) throws IOException {
return new String(readBytes(in), charset);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java | dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.function;
import java.util.function.Function;
/**
* {@link Function} with {@link Throwable}
*
* @param <T> the source type
* @param <R> the return type
* @see Function
* @see Throwable
* @since 2.7.5
*/
@FunctionalInterface
public interface ThrowableFunction<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
* @throws Throwable if met with any error
*/
R apply(T t) throws Throwable;
/**
* Executes {@link ThrowableFunction}
*
* @param t the function argument
* @return the function result
* @throws RuntimeException wrappers {@link Throwable}
*/
default R execute(T t) throws RuntimeException {
R result = null;
try {
result = apply(t);
} catch (Throwable e) {
throw new RuntimeException(e);
}
return result;
}
/**
* Executes {@link ThrowableFunction}
*
* @param t the function argument
* @param function {@link ThrowableFunction}
* @param <T> the source type
* @param <R> the return type
* @return the result after execution
*/
static <T, R> R execute(T t, ThrowableFunction<T, R> function) {
return function.execute(t);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java | dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.function;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.StreamSupport.stream;
import static org.apache.dubbo.common.function.Predicates.and;
import static org.apache.dubbo.common.function.Predicates.or;
/**
* The utilities class for {@link Stream}
*
* @since 2.7.5
*/
public interface Streams {
static <T, S extends Iterable<T>> Stream<T> filterStream(S values, Predicate<T> predicate) {
return stream(values.spliterator(), false).filter(predicate);
}
static <T, S extends Iterable<T>> List<T> filterList(S values, Predicate<T> predicate) {
return filterStream(values, predicate).collect(toList());
}
static <T, S extends Iterable<T>> Set<T> filterSet(S values, Predicate<T> predicate) {
// new Set with insertion order
return filterStream(values, predicate).collect(LinkedHashSet::new, Set::add, Set::addAll);
}
@SuppressWarnings("unchecked")
static <T, S extends Iterable<T>> S filter(S values, Predicate<T> predicate) {
final boolean isSet = Set.class.isAssignableFrom(values.getClass());
return (S) (isSet ? filterSet(values, predicate) : filterList(values, predicate));
}
static <T, S extends Iterable<T>> S filterAll(S values, Predicate<T>... predicates) {
return filter(values, and(predicates));
}
static <T, S extends Iterable<T>> S filterAny(S values, Predicate<T>... predicates) {
return filter(values, or(predicates));
}
static <T> T filterFirst(Iterable<T> values, Predicate<T>... predicates) {
return stream(values.spliterator(), false)
.filter(and(predicates))
.findFirst()
.orElse(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java | dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.function;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* {@link Consumer} with {@link Throwable}
*
* @param <T> the source type
* @see Function
* @see Throwable
* @since 2.7.5
*/
@FunctionalInterface
public interface ThrowableConsumer<T> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @throws Throwable if met with any error
*/
void accept(T t) throws Throwable;
/**
* Executes {@link ThrowableConsumer}
*
* @param t the function argument
* @throws RuntimeException wrappers {@link Throwable}
*/
default void execute(T t) throws RuntimeException {
try {
accept(t);
} catch (Throwable e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
/**
* Executes {@link ThrowableConsumer}
*
* @param t the function argument
* @param consumer {@link ThrowableConsumer}
* @param <T> the source type
*/
static <T> void execute(T t, ThrowableConsumer<T> consumer) {
consumer.execute(t);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java | dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.function;
import java.util.function.Predicate;
import static java.util.stream.Stream.of;
/**
* The utilities class for Java {@link Predicate}
*
* @since 2.7.5
*/
public interface Predicates {
Predicate[] EMPTY_ARRAY = new Predicate[0];
/**
* {@link Predicate} always return <code>true</code>
*
* @param <T> the type to test
* @return <code>true</code>
*/
static <T> Predicate<T> alwaysTrue() {
return e -> true;
}
/**
* {@link Predicate} always return <code>false</code>
*
* @param <T> the type to test
* @return <code>false</code>
*/
static <T> Predicate<T> alwaysFalse() {
return e -> false;
}
/**
* a composed predicate that represents a short-circuiting logical AND of {@link Predicate predicates}
*
* @param predicates {@link Predicate predicates}
* @param <T> the type to test
* @return non-null
*/
static <T> Predicate<T> and(Predicate<T>... predicates) {
return of(predicates).reduce(Predicate::and).orElseGet(Predicates::alwaysTrue);
}
/**
* a composed predicate that represents a short-circuiting logical OR of {@link Predicate predicates}
*
* @param predicates {@link Predicate predicates}
* @param <T> the detected type
* @return non-null
*/
static <T> Predicate<T> or(Predicate<T>... predicates) {
return of(predicates).reduce(Predicate::or).orElse(e -> true);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableAction.java | dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.function;
import java.util.function.Function;
/**
* A function interface for action with {@link Throwable}
*
* @see Function
* @see Throwable
* @since 2.7.5
*/
@FunctionalInterface
public interface ThrowableAction {
/**
* Executes the action
*
* @throws Throwable if met with error
*/
void execute() throws Throwable;
/**
* Executes {@link ThrowableAction}
*
* @param action {@link ThrowableAction}
* @throws RuntimeException wrap {@link Exception} to {@link RuntimeException}
*/
static void execute(ThrowableAction action) throws RuntimeException {
try {
action.execute();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java | dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.DefaultSerializeClassChecker;
import org.apache.dubbo.common.utils.LogHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
public final class JavaBeanSerializeUtil {
private static final Logger logger = LoggerFactory.getLogger(JavaBeanSerializeUtil.class);
private static final Map<String, Class<?>> TYPES = new HashMap<>();
private static final String ARRAY_PREFIX = "[";
private static final String REFERENCE_TYPE_PREFIX = "L";
private static final String REFERENCE_TYPE_SUFFIX = ";";
static {
TYPES.put(boolean.class.getName(), boolean.class);
TYPES.put(byte.class.getName(), byte.class);
TYPES.put(short.class.getName(), short.class);
TYPES.put(int.class.getName(), int.class);
TYPES.put(long.class.getName(), long.class);
TYPES.put(float.class.getName(), float.class);
TYPES.put(double.class.getName(), double.class);
TYPES.put(void.class.getName(), void.class);
TYPES.put("Z", boolean.class);
TYPES.put("B", byte.class);
TYPES.put("C", char.class);
TYPES.put("D", double.class);
TYPES.put("F", float.class);
TYPES.put("I", int.class);
TYPES.put("J", long.class);
TYPES.put("S", short.class);
}
private JavaBeanSerializeUtil() {}
public static JavaBeanDescriptor serialize(Object obj) {
return serialize(obj, JavaBeanAccessor.FIELD);
}
public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor) {
if (obj == null) {
return null;
}
if (obj instanceof JavaBeanDescriptor) {
return (JavaBeanDescriptor) obj;
}
IdentityHashMap<Object, JavaBeanDescriptor> cache = new IdentityHashMap<>();
return createDescriptorIfAbsent(obj, accessor, cache);
}
private static JavaBeanDescriptor createDescriptorForSerialize(Class<?> cl) {
if (cl.isEnum()) {
return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_ENUM);
}
if (cl.isArray()) {
return new JavaBeanDescriptor(cl.getComponentType().getName(), JavaBeanDescriptor.TYPE_ARRAY);
}
if (ReflectUtils.isPrimitive(cl)) {
return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
}
if (Class.class.equals(cl)) {
return new JavaBeanDescriptor(Class.class.getName(), JavaBeanDescriptor.TYPE_CLASS);
}
if (Collection.class.isAssignableFrom(cl)) {
return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_COLLECTION);
}
if (Map.class.isAssignableFrom(cl)) {
return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_MAP);
}
return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_BEAN);
}
private static JavaBeanDescriptor createDescriptorIfAbsent(
Object obj, JavaBeanAccessor accessor, IdentityHashMap<Object, JavaBeanDescriptor> cache) {
if (cache.containsKey(obj)) {
return cache.get(obj);
}
if (obj instanceof JavaBeanDescriptor) {
return (JavaBeanDescriptor) obj;
}
JavaBeanDescriptor result = createDescriptorForSerialize(obj.getClass());
cache.put(obj, result);
serializeInternal(result, obj, accessor, cache);
return result;
}
private static void serializeInternal(
JavaBeanDescriptor descriptor,
Object obj,
JavaBeanAccessor accessor,
IdentityHashMap<Object, JavaBeanDescriptor> cache) {
if (obj == null || descriptor == null) {
return;
}
if (obj.getClass().isEnum()) {
descriptor.setEnumNameProperty(((Enum<?>) obj).name());
} else if (ReflectUtils.isPrimitive(obj.getClass())) {
descriptor.setPrimitiveProperty(obj);
} else if (Class.class.equals(obj.getClass())) {
descriptor.setClassNameProperty(((Class<?>) obj).getName());
} else if (obj.getClass().isArray()) {
int len = Array.getLength(obj);
for (int i = 0; i < len; i++) {
Object item = Array.get(obj, i);
if (item == null) {
descriptor.setProperty(i, null);
} else {
JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache);
descriptor.setProperty(i, itemDescriptor);
}
}
} else if (obj instanceof Collection) {
Collection collection = (Collection) obj;
int index = 0;
for (Object item : collection) {
if (item == null) {
descriptor.setProperty(index++, null);
} else {
JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache);
descriptor.setProperty(index++, itemDescriptor);
}
}
} else if (obj instanceof Map) {
Map map = (Map) obj;
map.forEach((key, value) -> {
Object keyDescriptor = key == null ? null : createDescriptorIfAbsent(key, accessor, cache);
Object valueDescriptor = value == null ? null : createDescriptorIfAbsent(value, accessor, cache);
descriptor.setProperty(keyDescriptor, valueDescriptor);
}); // ~ end of loop map
} else {
if (JavaBeanAccessor.isAccessByMethod(accessor)) {
Map<String, Method> methods = ReflectUtils.getBeanPropertyReadMethods(obj.getClass());
for (Map.Entry<String, Method> entry : methods.entrySet()) {
try {
Object value = entry.getValue().invoke(obj);
if (value == null) {
continue;
}
JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache);
descriptor.setProperty(entry.getKey(), valueDescriptor);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} // ~ end of loop method map
} // ~ end of if (JavaBeanAccessor.isAccessByMethod(accessor))
if (JavaBeanAccessor.isAccessByField(accessor)) {
Map<String, Field> fields = ReflectUtils.getBeanPropertyFields(obj.getClass());
for (Map.Entry<String, Field> entry : fields.entrySet()) {
if (!descriptor.containsProperty(entry.getKey())) {
try {
Object value = entry.getValue().get(obj);
if (value == null) {
continue;
}
JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache);
descriptor.setProperty(entry.getKey(), valueDescriptor);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
} // ~ end of loop field map
} // ~ end of if (JavaBeanAccessor.isAccessByField(accessor))
} // ~ end of else
} // ~ end of method serializeInternal
public static Object deserialize(JavaBeanDescriptor beanDescriptor) {
return deserialize(beanDescriptor, Thread.currentThread().getContextClassLoader());
}
public static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader) {
if (beanDescriptor == null) {
return null;
}
IdentityHashMap<JavaBeanDescriptor, Object> cache = new IdentityHashMap<>();
Object result = instantiateForDeserialize(beanDescriptor, loader, cache);
deserializeInternal(result, beanDescriptor, loader, cache);
return result;
}
private static void deserializeInternal(
Object result,
JavaBeanDescriptor beanDescriptor,
ClassLoader loader,
IdentityHashMap<JavaBeanDescriptor, Object> cache) {
if (beanDescriptor.isEnumType() || beanDescriptor.isClassType() || beanDescriptor.isPrimitiveType()) {
return;
}
if (beanDescriptor.isArrayType()) {
int index = 0;
for (Map.Entry<Object, Object> entry : beanDescriptor) {
Object item = entry.getValue();
if (item instanceof JavaBeanDescriptor) {
JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue();
item = instantiateForDeserialize(itemDescriptor, loader, cache);
deserializeInternal(item, itemDescriptor, loader, cache);
}
Array.set(result, index++, item);
}
} else if (beanDescriptor.isCollectionType()) {
Collection collection = (Collection) result;
for (Map.Entry<Object, Object> entry : beanDescriptor) {
Object item = entry.getValue();
if (item instanceof JavaBeanDescriptor) {
JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue();
item = instantiateForDeserialize(itemDescriptor, loader, cache);
deserializeInternal(item, itemDescriptor, loader, cache);
}
collection.add(item);
}
} else if (beanDescriptor.isMapType()) {
Map map = (Map) result;
for (Map.Entry<Object, Object> entry : beanDescriptor) {
Object key = entry.getKey();
Object value = entry.getValue();
if (key instanceof JavaBeanDescriptor) {
JavaBeanDescriptor keyDescriptor = (JavaBeanDescriptor) entry.getKey();
key = instantiateForDeserialize(keyDescriptor, loader, cache);
deserializeInternal(key, keyDescriptor, loader, cache);
}
if (value instanceof JavaBeanDescriptor) {
JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue();
value = instantiateForDeserialize(valueDescriptor, loader, cache);
deserializeInternal(value, valueDescriptor, loader, cache);
}
map.put(key, value);
}
} else if (beanDescriptor.isBeanType()) {
for (Map.Entry<Object, Object> entry : beanDescriptor) {
String property = entry.getKey().toString();
Object value = entry.getValue();
if (value == null) {
continue;
}
if (value instanceof JavaBeanDescriptor) {
JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue();
value = instantiateForDeserialize(valueDescriptor, loader, cache);
deserializeInternal(value, valueDescriptor, loader, cache);
}
Method method = getSetterMethod(result.getClass(), property, value.getClass());
boolean setByMethod = false;
try {
if (method != null) {
method.invoke(result, value);
setByMethod = true;
}
} catch (Exception e) {
LogHelper.warn(logger, "Failed to set property through method " + method, e);
}
if (!setByMethod) {
try {
Field field = result.getClass().getField(property);
if (field != null) {
field.set(result, value);
}
} catch (NoSuchFieldException | IllegalAccessException e1) {
LogHelper.warn(logger, "Failed to set field value", e1);
}
}
}
} else {
throw new IllegalArgumentException(
"Unsupported type " + beanDescriptor.getClassName() + ":" + beanDescriptor.getType());
}
}
private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) {
String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
Method method = null;
try {
method = cls.getMethod(name, valueCls);
} catch (NoSuchMethodException e) {
for (Method m : cls.getMethods()) {
if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) {
method = m;
}
}
}
if (method != null) {
method.setAccessible(true);
}
return method;
}
private static Object instantiate(Class<?> cl) throws Exception {
Constructor<?>[] constructors = cl.getDeclaredConstructors();
Constructor<?> constructor = null;
int argc = Integer.MAX_VALUE;
for (Constructor<?> c : constructors) {
if (c.getParameterTypes().length < argc) {
argc = c.getParameterTypes().length;
constructor = c;
}
}
if (constructor != null) {
Class<?>[] paramTypes = constructor.getParameterTypes();
Object[] constructorArgs = new Object[paramTypes.length];
for (int i = 0; i < constructorArgs.length; i++) {
constructorArgs[i] = getConstructorArg(paramTypes[i]);
}
try {
constructor.setAccessible(true);
return constructor.newInstance(constructorArgs);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
LogHelper.warn(logger, e.getMessage(), e);
}
}
return cl.getDeclaredConstructor().newInstance();
}
public static Object getConstructorArg(Class<?> cl) {
if (boolean.class.equals(cl) || Boolean.class.equals(cl)) {
return Boolean.FALSE;
}
if (byte.class.equals(cl) || Byte.class.equals(cl)) {
return (byte) 0;
}
if (short.class.equals(cl) || Short.class.equals(cl)) {
return (short) 0;
}
if (int.class.equals(cl) || Integer.class.equals(cl)) {
return 0;
}
if (long.class.equals(cl) || Long.class.equals(cl)) {
return 0L;
}
if (float.class.equals(cl) || Float.class.equals(cl)) {
return (float) 0;
}
if (double.class.equals(cl) || Double.class.equals(cl)) {
return (double) 0;
}
if (char.class.equals(cl) || Character.class.equals(cl)) {
return (char) 0;
}
return null;
}
private static Object instantiateForDeserialize(
JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap<JavaBeanDescriptor, Object> cache) {
if (cache.containsKey(beanDescriptor)) {
return cache.get(beanDescriptor);
}
if (beanDescriptor.isClassType()) {
try {
return name2Class(loader, beanDescriptor.getClassNameProperty());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
if (beanDescriptor.isEnumType()) {
try {
Class<?> enumType = name2Class(loader, beanDescriptor.getClassName());
Method method = getEnumValueOfMethod(enumType);
return method.invoke(null, enumType, beanDescriptor.getEnumPropertyName());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
if (beanDescriptor.isPrimitiveType()) {
return beanDescriptor.getPrimitiveProperty();
}
Object result;
if (beanDescriptor.isArrayType()) {
Class<?> componentType;
try {
componentType = name2Class(loader, beanDescriptor.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
result = Array.newInstance(componentType, beanDescriptor.propertySize());
cache.put(beanDescriptor, result);
} else {
try {
Class<?> cl = name2Class(loader, beanDescriptor.getClassName());
result = instantiate(cl);
cache.put(beanDescriptor, result);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return result;
}
/**
* Transform the Class.forName String to Class Object.
*
* @param name Class.getName()
* @return Class
* @throws ClassNotFoundException Class.forName
*/
public static Class<?> name2Class(ClassLoader loader, String name) throws ClassNotFoundException {
if (TYPES.containsKey(name)) {
return TYPES.get(name);
}
if (isArray(name)) {
int dimension = 0;
while (isArray(name)) {
++dimension;
name = name.substring(1);
}
Class type = name2Class(loader, name);
int[] dimensions = new int[dimension];
for (int i = 0; i < dimension; i++) {
dimensions[i] = 0;
}
return Array.newInstance(type, dimensions).getClass();
}
if (isReferenceType(name)) {
name = name.substring(1, name.length() - 1);
}
return DefaultSerializeClassChecker.getInstance().loadClass(loader, name);
}
private static boolean isArray(String type) {
return type != null && type.startsWith(ARRAY_PREFIX);
}
private static boolean isReferenceType(String type) {
return type != null && type.startsWith(REFERENCE_TYPE_PREFIX) && type.endsWith(REFERENCE_TYPE_SUFFIX);
}
private static Method getEnumValueOfMethod(Class cl) throws NoSuchMethodException {
return cl.getMethod("valueOf", Class.class, String.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java | dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
public enum JavaBeanAccessor {
/**
* Field accessor.
*/
FIELD,
/**
* Method accessor.
*/
METHOD,
/**
* Method prefer to field.
*/
ALL;
public static boolean isAccessByMethod(JavaBeanAccessor accessor) {
return METHOD.equals(accessor) || ALL.equals(accessor);
}
public static boolean isAccessByField(JavaBeanAccessor accessor) {
return FIELD.equals(accessor) || ALL.equals(accessor);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java | dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public final class JavaBeanDescriptor implements Serializable, Iterable<Map.Entry<Object, Object>> {
private static final long serialVersionUID = -8505586483570518029L;
public static final int TYPE_CLASS = 1;
public static final int TYPE_ENUM = 2;
public static final int TYPE_COLLECTION = 3;
public static final int TYPE_MAP = 4;
public static final int TYPE_ARRAY = 5;
/**
* @see org.apache.dubbo.common.utils.ReflectUtils#isPrimitive(Class)
*/
public static final int TYPE_PRIMITIVE = 6;
public static final int TYPE_BEAN = 7;
private static final String ENUM_PROPERTY_NAME = "name";
private static final String CLASS_PROPERTY_NAME = "name";
private static final String PRIMITIVE_PROPERTY_VALUE = "value";
/**
* Used to define a type is valid.
*
* @see #isValidType(int)
*/
private static final int TYPE_MAX = TYPE_BEAN;
/**
* Used to define a type is valid.
*
* @see #isValidType(int)
*/
private static final int TYPE_MIN = TYPE_CLASS;
private String className;
private int type;
private final Map<Object, Object> properties = new LinkedHashMap<>();
public JavaBeanDescriptor() {}
public JavaBeanDescriptor(String className, int type) {
notEmpty(className, "class name is empty");
if (!isValidType(type)) {
throw new IllegalArgumentException("type [ " + type + " ] is unsupported");
}
this.className = className;
this.type = type;
}
public boolean isClassType() {
return TYPE_CLASS == type;
}
public boolean isEnumType() {
return TYPE_ENUM == type;
}
public boolean isCollectionType() {
return TYPE_COLLECTION == type;
}
public boolean isMapType() {
return TYPE_MAP == type;
}
public boolean isArrayType() {
return TYPE_ARRAY == type;
}
public boolean isPrimitiveType() {
return TYPE_PRIMITIVE == type;
}
public boolean isBeanType() {
return TYPE_BEAN == type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Object setProperty(Object propertyName, Object propertyValue) {
notNull(propertyName, "Property name is null");
return properties.put(propertyName, propertyValue);
}
public String setEnumNameProperty(String name) {
if (isEnumType()) {
Object result = setProperty(ENUM_PROPERTY_NAME, name);
return result == null ? null : result.toString();
}
throw new IllegalStateException("The instance is not a enum wrapper");
}
public String getEnumPropertyName() {
if (isEnumType()) {
Object result = getProperty(ENUM_PROPERTY_NAME);
return result == null ? null : result.toString();
}
throw new IllegalStateException("The instance is not a enum wrapper");
}
public String setClassNameProperty(String name) {
if (isClassType()) {
Object result = setProperty(CLASS_PROPERTY_NAME, name);
return result == null ? null : result.toString();
}
throw new IllegalStateException("The instance is not a class wrapper");
}
public String getClassNameProperty() {
if (isClassType()) {
Object result = getProperty(CLASS_PROPERTY_NAME);
return result == null ? null : result.toString();
}
throw new IllegalStateException("The instance is not a class wrapper");
}
public Object setPrimitiveProperty(Object primitiveValue) {
if (isPrimitiveType()) {
return setProperty(PRIMITIVE_PROPERTY_VALUE, primitiveValue);
}
throw new IllegalStateException("The instance is not a primitive type wrapper");
}
public Object getPrimitiveProperty() {
if (isPrimitiveType()) {
return getProperty(PRIMITIVE_PROPERTY_VALUE);
}
throw new IllegalStateException("The instance is not a primitive type wrapper");
}
public Object getProperty(Object propertyName) {
notNull(propertyName, "Property name is null");
return properties.get(propertyName);
}
public boolean containsProperty(Object propertyName) {
notNull(propertyName, "Property name is null");
return properties.containsKey(propertyName);
}
@Override
public Iterator<Map.Entry<Object, Object>> iterator() {
return properties.entrySet().iterator();
}
public int propertySize() {
return properties.size();
}
private boolean isValidType(int type) {
return TYPE_MIN <= type && type <= TYPE_MAX;
}
private void notNull(Object obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
private void notEmpty(String string, String message) {
if (isEmpty(string)) {
throw new IllegalArgumentException(message);
}
}
private boolean isEmpty(String string) {
return string == null || "".equals(string.trim());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.constants;
/**
* constant for Load-balance strategy
*/
public interface LoadbalanceRules {
/**
* This class select one provider from multiple providers randomly.
**/
String RANDOM = "random";
/**
* Round-robin load balance.
**/
String ROUND_ROBIN = "roundrobin";
/**
* Filter the number of invokers with the least number of active calls and count the weights and quantities of these invokers.
**/
String LEAST_ACTIVE = "leastactive";
/**
* Consistent Hash, requests with the same parameters are always sent to the same provider.
**/
String CONSISTENT_HASH = "consistenthash";
/**
* Filter the number of invokers with the shortest response time of success calls and count the weights and quantities of these invokers.
**/
String SHORTEST_RESPONSE = "shortestresponse";
/**
* adaptive load balance.
**/
String ADAPTIVE = "adaptive";
String EMPTY = "";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.constants;
public interface RemotingConstants {
String BACKUP_KEY = "backup";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.