proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/InternalComponentIdentifier.java
|
InternalComponentIdentifier
|
isInternal
|
class InternalComponentIdentifier {
private record Patterns(Pattern groupPattern, Pattern namePattern) {
private boolean hasPattern() {
return groupPattern != null || namePattern != null;
}
}
private final Supplier<Patterns> patternsSupplier = Suppliers.memoize(InternalComponentIdentifier::loadPatterns);
public boolean isInternal(final Component component) {<FILL_FUNCTION_BODY>}
private static Patterns loadPatterns() {
try (final var qm = new QueryManager()) {
final ConfigProperty groupsRegexProperty = qm.getConfigProperty(
INTERNAL_COMPONENTS_GROUPS_REGEX.getGroupName(),
INTERNAL_COMPONENTS_GROUPS_REGEX.getPropertyName()
);
final ConfigProperty namesRegexProperty = qm.getConfigProperty(
INTERNAL_COMPONENTS_NAMES_REGEX.getGroupName(),
INTERNAL_COMPONENTS_NAMES_REGEX.getPropertyName()
);
return new Patterns(
tryCompilePattern(groupsRegexProperty).orElse(null),
tryCompilePattern(namesRegexProperty).orElse(null)
);
}
}
private static Optional<Pattern> tryCompilePattern(final ConfigProperty property) {
return Optional.ofNullable(property)
.map(ConfigProperty::getPropertyValue)
.map(StringUtils::trimToNull)
.map(Pattern::compile);
}
}
|
final Patterns patterns = patternsSupplier.get();
if (!patterns.hasPattern()) {
return false;
}
final boolean matchesGroup;
if (isNotBlank(component.getGroup()) && patterns.groupPattern() != null) {
matchesGroup = patterns.groupPattern().matcher(component.getGroup()).matches();
} else {
matchesGroup = false;
}
final boolean matchesName;
if (isNotBlank(component.getName()) && patterns.namePattern() != null) {
matchesName = patterns.namePattern().matcher(component.getName()).matches();
} else {
matchesName = false;
}
return matchesGroup || matchesName;
| 381
| 181
| 562
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/JsonUtil.java
|
JsonUtil
|
add
|
class JsonUtil {
/**
* Private constructor.
*/
private JsonUtil() { }
public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final String value) {
if (value != null) {
builder.add(key, value);
}
return builder;
}
public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final BigInteger value) {<FILL_FUNCTION_BODY>}
public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final BigDecimal value) {
if (value != null) {
builder.add(key, value);
}
return builder;
}
public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final Enum value) {
if (value != null) {
builder.add(key, value.name());
}
return builder;
}
public static ZonedDateTime jsonStringToTimestamp(final String s) {
if (s == null) {
return null;
}
try {
return ZonedDateTime.parse(s);
} catch (DateTimeParseException e) {
return null;
}
}
}
|
if (value != null) {
builder.add(key, value);
}
return builder;
| 312
| 31
| 343
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/PersistenceUtil.java
|
Differ
|
applyIfNonEmptyAndChanged
|
class Differ<T> {
private final T existingObject;
private final T newObject;
private final Map<String, Diff> diffs;
public Differ(final T existingObject, final T newObject) {
this.existingObject = requireNonNull(existingObject, "existingObject must not be null");
this.newObject = requireNonNull(newObject, "newObject must not be null");
this.diffs = new HashMap<>();
}
/**
* Apply value of {@code newObject}'s field to value of {@code existingObject}'s field, if both values are different.
*
* @param fieldName Name of the field
* @param getter The getter to access current values with
* @param setter The setter on {@code existingObject}
* @param <V> Type of the values being compared
* @return {@code true} when changed, otherwise {@code false}
*/
public <V> boolean applyIfChanged(final String fieldName, final Function<T, V> getter, final Consumer<V> setter) {
final V existingValue = getter.apply(existingObject);
final V newValue = getter.apply(newObject);
if (!Objects.equals(existingValue, newValue)) {
diffs.put(fieldName, new Diff(existingValue, newValue));
setter.accept(newValue);
return true;
}
return false;
}
/**
* Apply value of {@code newObject}'s field to value of {@code existingObject}'s field, if {@code newObject}'s
* value is not {@code null}, and both values are different.
*
* @param fieldName Name of the field
* @param getter The getter to access current values with
* @param setter The setter on {@code existingObject}
* @param <V> Type of the values being compared
* @return {@code true} when changed, otherwise {@code false}
*/
public <V> boolean applyIfNonNullAndChanged(final String fieldName, final Function<T, V> getter, final Consumer<V> setter) {
final V existingValue = getter.apply(existingObject);
final V newValue = getter.apply(newObject);
if (newValue != null && !Objects.equals(existingValue, newValue)) {
diffs.put(fieldName, new Diff(existingValue, newValue));
setter.accept(newValue);
return true;
}
return false;
}
/**
* Apply value of {@code newObject}'s field to value of {@code existingObject}'s field, if both values are
* different, but not {@code null} or empty. In other words, {@code null} and empty are considered equal.
*
* @param fieldName Name of the field
* @param getter The getter to access current values with
* @param setter The setter on {@code existingObject}
* @param <V> Type of the items inside the {@link Collection} being compared
* @param <C> Type of the {@link Collection} being compared
* @return
*/
public <V, C extends Collection<V>> boolean applyIfNonEmptyAndChanged(final String fieldName, final Function<T, C> getter, final Consumer<C> setter) {<FILL_FUNCTION_BODY>}
public Map<String, Diff> getDiffs() {
return unmodifiableMap(diffs);
}
}
|
final C existingValue = getter.apply(existingObject);
final C newValue = getter.apply(newObject);
if (CollectionUtils.isEmpty(existingValue) && CollectionUtils.isEmpty(newValue)) {
return false;
}
if (!Objects.equals(existingValue, newValue)) {
diffs.put(fieldName, new Diff(existingValue, newValue));
setter.accept(newValue);
return true;
}
return false;
| 883
| 127
| 1,010
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/PurlUtil.java
|
PurlUtil
|
silentPurlCoordinatesOnly
|
class PurlUtil {
private PurlUtil() { }
public static PackageURL purlCoordinatesOnly(final PackageURL original) throws MalformedPackageURLException {
return aPackageURL()
.withType(original.getType())
.withNamespace(original.getNamespace())
.withName(original.getName())
.withVersion(original.getVersion())
.build();
}
public static PackageURL silentPurlCoordinatesOnly(final PackageURL original) {<FILL_FUNCTION_BODY>}
}
|
if (original == null) {
return null;
}
try {
return aPackageURL()
.withType(original.getType())
.withNamespace(original.getNamespace())
.withName(original.getName())
.withVersion(original.getVersion())
.build();
} catch (MalformedPackageURLException e) {
return null;
}
| 134
| 100
| 234
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/RetryUtil.java
|
RetryUtil
|
logRetryEventWith
|
class RetryUtil {
private static final Set<Class<? extends Throwable>> KNOWN_TRANSIENT_EXCEPTIONS = Set.of(
ConnectTimeoutException.class,
SocketTimeoutException.class,
TimeoutException.class
);
private static final Set<Integer> KNOWN_TRANSIENT_STATUS_CODES = Set.of(
HttpStatus.SC_TOO_MANY_REQUESTS,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
);
public static IntervalFunction withExponentialBackoff(final ConfigKey initialDurationConfigKey,
final ConfigKey multiplierConfigKey,
final ConfigKey maxDurationConfigKey) {
return IntervalFunction.ofExponentialBackoff(
Duration.ofMillis(Config.getInstance().getPropertyAsInt(initialDurationConfigKey)),
Config.getInstance().getPropertyAsInt(multiplierConfigKey),
Duration.ofMillis(Config.getInstance().getPropertyAsInt(maxDurationConfigKey))
);
}
public static <T extends RetryEvent> EventConsumer<T> logRetryEventWith(final Logger logger) {<FILL_FUNCTION_BODY>}
public static <T extends Closeable> BiConsumer<Integer, T> maybeClosePreviousResult() {
return (attempt, closeable) -> {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Predicate<CloseableHttpResponse> withTransientErrorCode() {
return response -> response != null
&& response.getStatusLine() != null
&& KNOWN_TRANSIENT_STATUS_CODES.contains(response.getStatusLine().getStatusCode());
}
public static Predicate<Throwable> withTransientCause() {
return withCauseAnyOf(KNOWN_TRANSIENT_EXCEPTIONS);
}
public static Predicate<Throwable> withCauseAnyOf(final Collection<Class<? extends Throwable>> causeClasses) {
return throwable -> {
for (final Throwable cause : ExceptionUtils.getThrowableList(throwable)) {
final boolean isMatch = causeClasses.stream()
.anyMatch(causeClass -> causeClass.isAssignableFrom(cause.getClass()));
if (isMatch) {
return true;
}
}
return false;
};
}
}
|
return event -> {
if (event instanceof final RetryOnRetryEvent retryEvent) {
final var message = "Encountered retryable error for %s; Will execute retry #%d in %s"
.formatted(event.getName(), event.getNumberOfRetryAttempts(), retryEvent.getWaitInterval());
if (event.getLastThrowable() != null) {
logger.warn(message, event.getLastThrowable());
} else {
logger.warn(message);
}
} else if (event instanceof final RetryOnErrorEvent errorEvent) {
final var message = "Max retry attempts exceeded for %s after %d attempts"
.formatted(errorEvent.getName(), errorEvent.getNumberOfRetryAttempts());
if (errorEvent.getLastThrowable() != null) {
logger.error(message, errorEvent.getLastThrowable());
} else {
logger.error(message);
}
} else if (event instanceof final RetryOnIgnoredErrorEvent ignoredErrorEvent) {
if (!logger.isDebugEnabled()) {
return;
}
final var message = "Ignored error for %s after %d attempts; Will not retry"
.formatted(event.getName(), event.getNumberOfRetryAttempts());
if (event.getLastThrowable() != null) {
logger.debug(message, event.getLastThrowable());
} else {
logger.debug(message);
}
}
};
| 663
| 380
| 1,043
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/RoundRobinAccessor.java
|
RoundRobinAccessor
|
get
|
class RoundRobinAccessor<T> {
private final List<T> list;
private final AtomicInteger index;
public RoundRobinAccessor(final List<T> list) {
this(list, new AtomicInteger());
}
RoundRobinAccessor(final List<T> list, final AtomicInteger index) {
this.list = Collections.unmodifiableList(list);
this.index = index;
}
public T get() {<FILL_FUNCTION_BODY>}
}
|
// "& Integer.MAX_VALUE" resets the sign should x overflow.
// https://engineering.atspotify.com/2015/08/underflow-bug/
return list.get(index.getAndUpdate(x -> (x + 1) & Integer.MAX_VALUE) % list.size());
| 136
| 82
| 218
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/XmlUtil.java
|
XmlUtil
|
buildSecureSaxParser
|
class XmlUtil {
private XmlUtil() { }
/**
* Constructs a validating secure SAX Parser.
*
* @param schemaStream One or more inputStreams with the schema(s) that the
* parser should be able to validate the XML against, one InputStream per
* schema
* @return a SAX Parser
* @throws javax.xml.parsers.ParserConfigurationException is thrown if there
* is a parser configuration exception
* @throws org.xml.sax.SAXNotRecognizedException thrown if there is an
* unrecognized feature
* @throws org.xml.sax.SAXNotSupportedException thrown if there is a
* non-supported feature
* @throws org.xml.sax.SAXException is thrown if there is a
* org.xml.sax.SAXException
*/
public static SAXParser buildSecureSaxParser(InputStream... schemaStream) throws ParserConfigurationException,
SAXNotRecognizedException, SAXNotSupportedException, SAXException {<FILL_FUNCTION_BODY>}
/**
* Constructs a secure SAX Parser.
*
* @return a SAX Parser
* @throws javax.xml.parsers.ParserConfigurationException thrown if there is
* a parser configuration exception
* @throws org.xml.sax.SAXNotRecognizedException thrown if there is an
* unrecognized feature
* @throws org.xml.sax.SAXNotSupportedException thrown if there is a
* non-supported feature
* @throws org.xml.sax.SAXException is thrown if there is a
* org.xml.sax.SAXException
*/
public static SAXParser buildSecureSaxParser() throws ParserConfigurationException,
SAXNotRecognizedException, SAXNotSupportedException, SAXException {
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
return factory.newSAXParser();
}
/**
* Constructs a new document builder with security features enabled.
*
* @return a new document builder
* @throws javax.xml.parsers.ParserConfigurationException thrown if there is
* a parser configuration exception
*/
public static DocumentBuilder buildSecureDocumentBuilder() throws ParserConfigurationException {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
return factory.newDocumentBuilder();
}
}
|
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
System.setProperty("javax.xml.accessExternalSchema", "file, https");
final SAXParser saxParser = factory.newSAXParser();
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream);
return saxParser;
| 761
| 308
| 1,069
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-brpc/src/main/java/org/dromara/dynamictp/apapter/brpc/client/StarlightClientDtpAdapter.java
|
StarlightClientDtpAdapter
|
initialize
|
class StarlightClientDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "brpcClientTp";
private static final String THREAD_POOL_FIELD = "threadPoolOfAll";
private static final String DEFAULT_THREAD_POOL_FIELD = "defaultThreadPool";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getBrpcTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
}
|
super.initialize();
List<StarlightClient> starlightClients = JVMTI.getInstances(StarlightClient.class);
if (CollectionUtils.isEmpty(starlightClients)) {
log.warn("Cannot find beans of type StarlightClient.");
return;
}
starlightClients.forEach(v -> {
val threadPoolFactory = (ThreadPoolFactory) ReflectionUtil.getFieldValue(SingleStarlightClient.class,
THREAD_POOL_FIELD, v);
if (Objects.isNull(threadPoolFactory)) {
return;
}
String tpName = TP_PREFIX + "#" + v.remoteURI().getParameter("biz_thread_pool_name");
val executor = threadPoolFactory.defaultThreadPool();
if (Objects.nonNull(executor)) {
enhanceOriginExecutor(tpName, executor, DEFAULT_THREAD_POOL_FIELD, threadPoolFactory);
}
});
| 174
| 244
| 418
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-brpc/src/main/java/org/dromara/dynamictp/apapter/brpc/server/StarlightServerDtpAdapter.java
|
StarlightServerDtpAdapter
|
initialize
|
class StarlightServerDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "brpcServerTp";
private static final String URI_FIELD = "uri";
private static final String SERVER_PEER_FIELD = "serverPeer";
private static final String THREAD_POOL_FACTORY_FIELD = "threadPoolFactory";
private static final String DEFAULT_THREAD_POOL_FIELD = "defaultThreadPool";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getBrpcTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
}
|
super.initialize();
val bean = JVMTI.getInstance(StarlightServer.class);
if (!(bean instanceof DefaultStarlightServer)) {
return;
}
val starlightServer = (DefaultStarlightServer) bean;
val uri = (URI) ReflectionUtil.getFieldValue(DefaultStarlightServer.class, URI_FIELD, starlightServer);
val serverPeer = (ServerPeer) ReflectionUtil.getFieldValue(DefaultStarlightServer.class,
SERVER_PEER_FIELD, starlightServer);
if (Objects.isNull(uri) || Objects.isNull(serverPeer) || !(serverPeer instanceof NettyServer)) {
return;
}
val processor = (ServerProcessor) serverPeer.getProcessor();
if (Objects.isNull(processor)) {
return;
}
val threadPoolFactory = (ThreadPoolFactory) ReflectionUtil.getFieldValue(ServerProcessor.class,
THREAD_POOL_FACTORY_FIELD, processor);
if (Objects.isNull(threadPoolFactory)) {
return;
}
String tpName = TP_PREFIX + "#" + uri.getParameter("biz_thread_pool_name");
val executor = threadPoolFactory.defaultThreadPool();
if (Objects.nonNull(executor)) {
enhanceOriginExecutor(tpName, executor, DEFAULT_THREAD_POOL_FIELD, threadPoolFactory);
}
| 211
| 360
| 571
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-common/src/main/java/org/dromara/dynamictp/adapter/common/AbstractDtpAdapter.java
|
AbstractDtpAdapter
|
refresh
|
class AbstractDtpAdapter extends OnceApplicationContextEventListener implements DtpAdapter {
private static final Equator EQUATOR = new GetterBaseEquator();
protected final Map<String, ExecutorWrapper> executors = Maps.newHashMap();
@Override
protected void onContextRefreshedEvent(ContextRefreshedEvent event) {
try {
DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
initialize();
afterInitialize();
refresh(dtpProperties);
log.info("DynamicTp adapter, {} init end, executors: {}", getTpPrefix(), executors);
} catch (Throwable e) {
log.error("DynamicTp adapter, {} init failed.", getTpPrefix(), e);
}
}
protected void initialize() {
}
protected void afterInitialize() {
getExecutorWrappers().forEach((k, v) -> AwareManager.register(v));
}
@Override
public Map<String, ExecutorWrapper> getExecutorWrappers() {
return executors;
}
/**
* Get multi thread pool stats.
*
* @return thead pools stats
*/
@Override
public List<ThreadPoolStats> getMultiPoolStats() {
val executorWrappers = getExecutorWrappers();
if (MapUtils.isEmpty(executorWrappers)) {
return Collections.emptyList();
}
List<ThreadPoolStats> threadPoolStats = Lists.newArrayList();
executorWrappers.forEach((k, v) -> threadPoolStats.add(ExecutorConverter.toMetrics(v)));
return threadPoolStats;
}
public void refresh(List<TpExecutorProps> propsList, List<NotifyPlatform> platforms) {
val executorWrappers = getExecutorWrappers();
if (CollectionUtils.isEmpty(propsList) || MapUtils.isEmpty(executorWrappers)) {
return;
}
val tmpMap = StreamUtil.toMap(propsList, TpExecutorProps::getThreadPoolName);
executorWrappers.forEach((k, v) -> refresh(v, platforms, tmpMap.get(k)));
}
public void refresh(ExecutorWrapper executorWrapper, List<NotifyPlatform> platforms, TpExecutorProps props) {<FILL_FUNCTION_BODY>}
protected TpMainFields getTpMainFields(ExecutorWrapper executorWrapper, TpExecutorProps props) {
return ExecutorConverter.toMainFields(executorWrapper);
}
/**
* Get tp prefix.
* @return tp prefix
*/
protected abstract String getTpPrefix();
protected void enhanceOriginExecutor(String tpName, ThreadPoolExecutor executor, String fieldName, Object targetObj) {
ThreadPoolExecutorProxy proxy = new ThreadPoolExecutorProxy(executor);
try {
ReflectionUtil.setFieldValue(fieldName, targetObj, proxy);
putAndFinalize(tpName, executor, proxy);
} catch (IllegalAccessException e) {
log.error("DynamicTp adapter, enhance {} failed.", tpName, e);
}
}
protected void putAndFinalize(String tpName, ExecutorService origin, Executor targetForWrapper) {
executors.put(tpName, new ExecutorWrapper(tpName, targetForWrapper));
shutdownOriginalExecutor(origin);
}
protected void shutdownOriginalExecutor(ExecutorService executor) {
shutdownGracefulAsync(executor, getTpPrefix(), 5);
}
protected void doRefresh(ExecutorWrapper executorWrapper,
List<NotifyPlatform> platforms,
TpExecutorProps props) {
val executor = executorWrapper.getExecutor();
doRefreshPoolSize(executor, props);
if (!Objects.equals(executor.getKeepAliveTime(props.getUnit()), props.getKeepAliveTime())) {
executor.setKeepAliveTime(props.getKeepAliveTime(), props.getUnit());
}
if (StringUtils.isNotBlank(props.getThreadPoolAliasName())) {
executorWrapper.setThreadPoolAliasName(props.getThreadPoolAliasName());
}
List<TaskWrapper> taskWrappers = TaskWrappers.getInstance().getByNames(props.getTaskWrapperNames());
executorWrapper.setTaskWrappers(taskWrappers);
// update notify items
updateNotifyInfo(executorWrapper, props, platforms);
// update aware related
AwareManager.refresh(executorWrapper, props);
}
private void doRefreshPoolSize(ExecutorAdapter<?> executor, TpExecutorProps props) {
if (props.getMaximumPoolSize() >= executor.getMaximumPoolSize()) {
if (!Objects.equals(props.getMaximumPoolSize(), executor.getMaximumPoolSize())) {
executor.setMaximumPoolSize(props.getMaximumPoolSize());
}
if (!Objects.equals(props.getCorePoolSize(), executor.getCorePoolSize())) {
executor.setCorePoolSize(props.getCorePoolSize());
}
return;
}
if (!Objects.equals(props.getCorePoolSize(), executor.getCorePoolSize())) {
executor.setCorePoolSize(props.getCorePoolSize());
}
if (!Objects.equals(props.getMaximumPoolSize(), executor.getMaximumPoolSize())) {
executor.setMaximumPoolSize(props.getMaximumPoolSize());
}
}
}
|
if (Objects.isNull(props) || Objects.isNull(executorWrapper) || containsInvalidParams(props, log)) {
return;
}
TpMainFields oldFields = getTpMainFields(executorWrapper, props);
doRefresh(executorWrapper, platforms, props);
TpMainFields newFields = getTpMainFields(executorWrapper, props);
if (oldFields.equals(newFields)) {
log.debug("DynamicTp adapter, main properties of [{}] have not changed.",
executorWrapper.getThreadPoolName());
return;
}
List<FieldInfo> diffFields = EQUATOR.getDiffFields(oldFields, newFields);
List<String> diffKeys = diffFields.stream().map(FieldInfo::getFieldName).collect(toList());
NoticeManager.tryNoticeAsync(executorWrapper, oldFields, diffKeys);
log.info("DynamicTp adapter, [{}] refreshed end, changed keys: {}, corePoolSize: [{}], "
+ "maxPoolSize: [{}], keepAliveTime: [{}]",
executorWrapper.getThreadPoolName(), diffKeys,
String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldFields.getCorePoolSize(), newFields.getCorePoolSize()),
String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldFields.getMaxPoolSize(), newFields.getMaxPoolSize()),
String.format(PROPERTIES_CHANGE_SHOW_STYLE, oldFields.getKeepAliveTime(), newFields.getKeepAliveTime()));
| 1,394
| 398
| 1,792
|
<methods>public void onApplicationEvent(ApplicationEvent) ,public final void setApplicationContext(ApplicationContext) <variables>private ApplicationContext applicationContext
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-common/src/main/java/org/dromara/dynamictp/adapter/common/DtpAdapterListener.java
|
DtpAdapterListener
|
onApplicationEvent
|
class DtpAdapterListener implements GenericApplicationListener {
@Override
public boolean supportsEventType(ResolvableType resolvableType) {
Class<?> type = resolvableType.getRawClass();
if (type != null) {
return RefreshEvent.class.isAssignableFrom(type)
|| CollectEvent.class.isAssignableFrom(type)
|| AlarmCheckEvent.class.isAssignableFrom(type);
}
return false;
}
@Override
public void onApplicationEvent(@NonNull ApplicationEvent event) {<FILL_FUNCTION_BODY>}
/**
* Compatible with lower versions of spring.
*
* @param sourceType sourceType
* @return true if support
*/
@Override
public boolean supportsSourceType(@Nullable Class<?> sourceType) {
return true;
}
/**
* Compatible with lower versions of spring.
*
* @return order
*/
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
/**
* Do collect thread pool stats.
* @param dtpProperties dtpProperties
*/
protected void doCollect(DtpProperties dtpProperties) {
val handlerMap = ApplicationContextHolder.getBeansOfType(DtpAdapter.class);
if (CollectionUtils.isEmpty(handlerMap)) {
return;
}
handlerMap.forEach((k, v) -> v.getMultiPoolStats().forEach(ps ->
CollectorHandler.getInstance().collect(ps, dtpProperties.getCollectorTypes())));
}
/**
* Do refresh.
* @param dtpProperties dtpProperties
*/
protected void doRefresh(DtpProperties dtpProperties) {
val handlerMap = ApplicationContextHolder.getBeansOfType(DtpAdapter.class);
if (CollectionUtils.isEmpty(handlerMap)) {
return;
}
handlerMap.forEach((k, v) -> v.refresh(dtpProperties));
}
/**
* Do alarm check.
* @param dtpProperties dtpProperties
*/
protected void doAlarmCheck(DtpProperties dtpProperties) {
val handlerMap = ApplicationContextHolder.getBeansOfType(DtpAdapter.class);
if (CollectionUtils.isEmpty(handlerMap)) {
return;
}
handlerMap.forEach((k, v) -> {
val executorWrapper = v.getExecutorWrappers();
executorWrapper.forEach((kk, vv) -> AlarmManager.tryAlarmAsync(vv, SCHEDULE_NOTIFY_ITEMS));
});
}
}
|
try {
if (event instanceof RefreshEvent) {
doRefresh(((RefreshEvent) event).getDtpProperties());
} else if (event instanceof CollectEvent) {
doCollect(((CollectEvent) event).getDtpProperties());
} else if (event instanceof AlarmCheckEvent) {
doAlarmCheck(((AlarmCheckEvent) event).getDtpProperties());
}
} catch (Exception e) {
log.error("DynamicTp adapter, event handle failed.", e);
}
| 676
| 130
| 806
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-dubbo/src/main/java/org/dromara/dynamictp/adapter/dubbo/alibaba/AlibabaDubboDtpAdapter.java
|
AlibabaDubboDtpAdapter
|
initialize
|
class AlibabaDubboDtpAdapter extends AbstractDtpAdapter implements InitializingBean {
private static final String TP_PREFIX = "dubboTp";
private static final String EXECUTOR_FIELD = "executor";
private final AtomicBoolean registered = new AtomicBoolean(false);
@Override
public void afterPropertiesSet() throws Exception {
//从ApplicationReadyEvent改为ContextRefreshedEvent后,
//启动时无法dubbo获取线程池,这里直接每隔1s轮循,直至成功初始化线程池
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
while (!registered.get()) {
try {
Thread.sleep(1000);
DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
this.initialize();
this.refresh(dtpProperties);
} catch (Throwable e) { }
}
});
executor.shutdown();
}
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getDubboTp(), dtpProperties.getPlatforms());
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
private String genTpName(String port) {
return TP_PREFIX + "#" + port;
}
}
|
super.initialize();
val handlers = JVMTI.getInstances(WrappedChannelHandler.class);
if (CollectionUtils.isNotEmpty(handlers) && registered.compareAndSet(false, true)) {
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
handlers.forEach(handler -> {
val executor = handler.getExecutor();
if (executor instanceof ThreadPoolExecutor) {
String port = String.valueOf(handler.getUrl().getPort());
String tpName = genTpName(port);
enhanceOriginExecutor(tpName, (ThreadPoolExecutor) executor, EXECUTOR_FIELD, handler);
dataStore.put(EXECUTOR_SERVICE_COMPONENT_KEY, port, handler.getExecutor());
}
});
}
| 388
| 209
| 597
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-dubbo/src/main/java/org/dromara/dynamictp/adapter/dubbo/apache/ApacheDubboDtpAdapter.java
|
ApacheDubboDtpAdapter
|
initialize
|
class ApacheDubboDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "dubboTp";
private static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName();
private static final String EXECUTOR_FIELD = "executor";
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ServiceBeanExportedEvent) {
try {
DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
initialize();
refresh(dtpProperties);
} catch (Exception e) {
log.error("DynamicTp adapter, {} init failed.", getTpPrefix(), e);
}
}
}
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getDubboTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
private ThreadPoolExecutor getProxy(Executor executor) {
ThreadPoolExecutor proxy;
if (executor instanceof EagerThreadPoolExecutor) {
proxy = new EagerThreadPoolExecutorProxy((EagerThreadPoolExecutor) executor);
} else {
proxy = new ThreadPoolExecutorProxy((ThreadPoolExecutor) executor);
}
return proxy;
}
private String genTpName(String port) {
return TP_PREFIX + "#" + port;
}
}
|
super.initialize();
String currVersion = Version.getVersion();
if (DubboVersion.compare(DubboVersion.VERSION_2_7_5, currVersion) > 0) {
// 当前dubbo版本 < 2.7.5
val handlers = JVMTI.getInstances(WrappedChannelHandler.class);
if (CollectionUtils.isEmpty(handlers)) {
return;
}
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
handlers.forEach(handler -> {
//获取WrappedChannelHandler中的原始线程池
val originExecutor = ReflectionUtil.getFieldValue(EXECUTOR_FIELD, handler);
if (!(originExecutor instanceof ExecutorService)) {
return;
}
URL url = handler.getUrl();
//低版本跳过消费者线程池配置
if (!CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) {
String port = String.valueOf(url.getPort());
String tpName = genTpName(port);
//增强原始线程池,替换为动态线程池代理
enhanceOriginExecutor(tpName, (ThreadPoolExecutor) originExecutor, EXECUTOR_FIELD, handler);
//获取增强后的新动态线程池
Object newExexutor = ReflectionUtil.getFieldValue(EXECUTOR_FIELD, handler);
//替换dataStore中的线程池
dataStore.put(EXECUTOR_SERVICE_COMPONENT_KEY, port, newExexutor);
}
});
return;
}
ExecutorRepository executorRepository;
if (DubboVersion.compare(currVersion, DubboVersion.VERSION_3_0_3) >= 0) {
// 当前dubbo版本 >= 3.0.3
executorRepository = ApplicationModel.defaultModel().getExtensionLoader(ExecutorRepository.class).getDefaultExtension();
} else {
// 2.7.5 <= 当前dubbo版本 < 3.0.3
executorRepository = ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension();
}
val data = (ConcurrentMap<String, ConcurrentMap<Object, ExecutorService>>) ReflectionUtil.getFieldValue(
DefaultExecutorRepository.class, "data", executorRepository);
if (Objects.isNull(data)) {
return;
}
Map<Object, ExecutorService> executorMap = data.get(EXECUTOR_SERVICE_COMPONENT_KEY);
if (MapUtils.isNotEmpty(executorMap)) {
executorMap.forEach((k, v) -> {
ThreadPoolExecutor proxy = getProxy(v);
executorMap.replace(k, proxy);
putAndFinalize(genTpName(k.toString()), (ExecutorService) v, proxy);
});
}
| 409
| 730
| 1,139
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-grpc/src/main/java/org/dromara/dynamictp/adapter/grpc/GrpcDtpAdapter.java
|
GrpcDtpAdapter
|
initialize
|
class GrpcDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "grpcTp";
private static final String SERVER_FIELD = "transportServer";
private static final String EXECUTOR_FIELD = "executor";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getGrpcTp(), dtpProperties.getPlatforms());
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
private String genTpName(String key) {
return TP_PREFIX + "#" + key;
}
}
|
val beans = JVMTI.getInstances(ServerImpl.class);
if (CollectionUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type ServerImpl.");
return;
}
for (val serverImpl : beans) {
val internalServer = (InternalServer) ReflectionUtil.getFieldValue(ServerImpl.class, SERVER_FIELD, serverImpl);
String key = Optional.ofNullable(internalServer)
.map(server -> {
final SocketAddress address = server.getListenSocketAddress();
if (address instanceof InetSocketAddress) {
return String.valueOf(((InetSocketAddress) address).getPort());
} else if (address instanceof InProcessSocketAddress) {
return ((InProcessSocketAddress) address).getName();
}
return null;
}).orElse(null);
if (Objects.isNull(key)) {
continue;
}
val executor = (Executor) ReflectionUtil.getFieldValue(ServerImpl.class, EXECUTOR_FIELD, serverImpl);
if (Objects.nonNull(executor) && executor instanceof ThreadPoolExecutor) {
enhanceOriginExecutor(genTpName(key), (ThreadPoolExecutor) executor, EXECUTOR_FIELD, serverImpl);
}
}
| 194
| 318
| 512
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-hystrix/src/main/java/org/dromara/dynamictp/adapter/hystrix/DtpHystrixMetricsPublisher.java
|
DtpHystrixMetricsPublisher
|
getMetricsPublisherForThreadPool
|
class DtpHystrixMetricsPublisher extends HystrixMetricsPublisher {
private final HystrixMetricsPublisher metricsPublisher;
public DtpHystrixMetricsPublisher(HystrixMetricsPublisher metricsPublisher) {
this.metricsPublisher = metricsPublisher;
}
@Override
public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixThreadPoolMetrics metrics,
HystrixThreadPoolProperties properties) {<FILL_FUNCTION_BODY>}
}
|
val metricsPublisherForThreadPool =
metricsPublisher.getMetricsPublisherForThreadPool(threadPoolKey, metrics, properties);
return new DtpMetricsPublisherThreadPool(threadPoolKey, metrics, properties, metricsPublisherForThreadPool);
| 143
| 62
| 205
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-hystrix/src/main/java/org/dromara/dynamictp/adapter/hystrix/DtpMetricsPublisherThreadPool.java
|
DtpMetricsPublisherThreadPool
|
refreshProperties
|
class DtpMetricsPublisherThreadPool implements HystrixMetricsPublisherThreadPool {
private static final String PROPERTY_PREFIX = "hystrix";
private static final int DEFAULT_CORE_SIZE = 10;
private static final int DEFAULT_MAXIMUM_SIZE = 10;
private static final int DEFAULT_KEEP_ALIVE_TIME_MINUTES = 1;
private final AtomicBoolean init = new AtomicBoolean(false);
private final HystrixThreadPoolKey threadPoolKey;
private final HystrixThreadPoolMetrics metrics;
private final HystrixThreadPoolProperties threadPoolProperties;
private final HystrixMetricsPublisherThreadPool metricsPublisherForThreadPool;
public DtpMetricsPublisherThreadPool(
final HystrixThreadPoolKey threadPoolKey,
final HystrixThreadPoolMetrics metrics,
final HystrixThreadPoolProperties threadPoolProperties,
final HystrixMetricsPublisherThreadPool metricsPublisherForThreadPool) {
this.threadPoolKey = threadPoolKey;
this.metrics = metrics;
this.threadPoolProperties = threadPoolProperties;
this.metricsPublisherForThreadPool = metricsPublisherForThreadPool;
}
@Override
public void initialize() {
metricsPublisherForThreadPool.initialize();
HystrixDtpAdapter hystrixTpHandler = ApplicationContextHolder.getBean(HystrixDtpAdapter.class);
hystrixTpHandler.cacheMetricsPublisher(threadPoolKey.name(), this);
hystrixTpHandler.register(threadPoolKey.name(), metrics);
}
public void refreshProperties(TpExecutorProps props) {<FILL_FUNCTION_BODY>}
private static HystrixProperty<Integer> getProperty(HystrixThreadPoolKey key,
String instanceProperty,
Integer builderOverrideValue,
Integer defaultValue) {
return forInteger()
.add(getPropertyName(key.name(), instanceProperty), builderOverrideValue)
.add(getDefaultPropertyName(instanceProperty), defaultValue)
.build();
}
private static HystrixProperty<Boolean> getProperty(HystrixThreadPoolKey key,
String instanceProperty,
Boolean builderOverrideValue,
Boolean defaultValue) {
return forBoolean()
.add(getPropertyName(key.name(), instanceProperty), builderOverrideValue)
.add(getDefaultPropertyName(instanceProperty), defaultValue)
.build();
}
private static String getPropertyName(String key, String instanceProperty) {
return PROPERTY_PREFIX + ".threadpool." + key + "." + instanceProperty;
}
private static String getDefaultPropertyName(String instanceProperty) {
return PROPERTY_PREFIX + ".threadpool.default." + instanceProperty;
}
}
|
if (Objects.isNull(props)) {
return;
}
try {
if (!Objects.equals(threadPoolProperties.coreSize().get(), props.getCorePoolSize())) {
val corePoolSize = getProperty(threadPoolKey, "coreSize",
props.getCorePoolSize(), DEFAULT_CORE_SIZE);
ReflectionUtil.setFieldValue(HystrixThreadPoolProperties.class,
"corePoolSize", threadPoolProperties, corePoolSize);
}
if (!Objects.equals(threadPoolProperties.maximumSize().get(), props.getMaximumPoolSize())) {
val maxPoolSize = getProperty(threadPoolKey, "maximumSize",
props.getMaximumPoolSize(), DEFAULT_MAXIMUM_SIZE);
ReflectionUtil.setFieldValue(HystrixThreadPoolProperties.class,
"maximumPoolSize", threadPoolProperties, maxPoolSize);
}
val keepAliveTimeMinutes = (int) TimeUnit.SECONDS.toMinutes(props.getKeepAliveTime());
if (!Objects.equals(threadPoolProperties.keepAliveTimeMinutes().get(), keepAliveTimeMinutes)) {
val keepAliveTimeProperty = getProperty(threadPoolKey,
"keepAliveTimeMinutes", keepAliveTimeMinutes, DEFAULT_KEEP_ALIVE_TIME_MINUTES);
ReflectionUtil.setFieldValue(HystrixThreadPoolProperties.class,
"keepAliveTime", threadPoolProperties, keepAliveTimeProperty);
}
if (init.compareAndSet(false, true)) {
val allowSetMax = getProperty(threadPoolKey,
"allowMaximumSizeToDivergeFromCoreSize", true, true);
ReflectionUtil.setFieldValue(HystrixThreadPoolProperties.class,
"allowMaximumSizeToDivergeFromCoreSize", threadPoolProperties, allowSetMax);
}
} catch (IllegalAccessException e) {
log.error("DynamicTp hystrix adapter, reset hystrix threadPool properties failed.", e);
}
| 700
| 510
| 1,210
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-hystrix/src/main/java/org/dromara/dynamictp/adapter/hystrix/HystrixDtpAdapter.java
|
HystrixDtpAdapter
|
register
|
class HystrixDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "hystrixTp";
private static final String THREAD_POOL_FIELD = "threadPool";
private static final Map<String, DtpMetricsPublisherThreadPool> METRICS_PUBLISHERS = Maps.newHashMap();
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getHystrixTp(), dtpProperties.getPlatforms());
}
@Override
public void refresh(ExecutorWrapper executorWrapper, List<NotifyPlatform> platforms, TpExecutorProps props) {
super.refresh(executorWrapper, platforms, props);
val metricsPublisher = METRICS_PUBLISHERS.get(executorWrapper.getThreadPoolName());
if (Objects.isNull(metricsPublisher)) {
return;
}
metricsPublisher.refreshProperties(props);
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
public void register(String poolName, HystrixThreadPoolMetrics metrics) {<FILL_FUNCTION_BODY>}
public void cacheMetricsPublisher(String poolName, DtpMetricsPublisherThreadPool metricsPublisher) {
METRICS_PUBLISHERS.putIfAbsent(poolName, metricsPublisher);
}
@Override
protected void initialize() {
super.initialize();
HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance().getCommandExecutionHook();
HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
HystrixPlugins.reset();
HystrixPlugins.getInstance().registerMetricsPublisher(new DtpHystrixMetricsPublisher(metricsPublisher));
HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy);
HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
}
}
|
ThreadPoolExecutor threadPoolExecutor = metrics.getThreadPool();
if (executors.containsKey(poolName)) {
return;
}
DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
val prop = StreamUtil.toMap(dtpProperties.getHystrixTp(), TpExecutorProps::getThreadPoolName);
String tpName = TP_PREFIX + "#" + poolName;
enhanceOriginExecutor(tpName, threadPoolExecutor, THREAD_POOL_FIELD, metrics);
refresh(executors.get(tpName), dtpProperties.getPlatforms(), prop.get(tpName));
log.info("DynamicTp adapter, {} init end, executor {}", getTpPrefix(), executors.get(tpName));
| 633
| 195
| 828
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-motan/src/main/java/org/dromara/dynamictp/adapter/motan/MotanDtpAdapter.java
|
MotanDtpAdapter
|
initialize
|
class MotanDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "motanTp";
private static final String SERVER_FIELD = "server";
private static final String EXECUTOR_FIELD = "standardThreadExecutor";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getMotanTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
}
|
super.initialize();
val beans = ApplicationContextHolder.getBeansOfType(ServiceConfigBean.class);
if (MapUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type ServiceConfigBean.");
return;
}
beans.forEach((k, v) -> {
List<Exporter<?>> exporters = v.getExporters();
if (CollectionUtils.isEmpty(exporters)) {
return;
}
exporters.forEach(e -> {
if (!(e instanceof DefaultRpcExporter)) {
return;
}
val defaultRpcExporter = (DefaultRpcExporter<?>) e;
val server = (Server) ReflectionUtil.getFieldValue(DefaultRpcExporter.class, SERVER_FIELD, defaultRpcExporter);
if (Objects.isNull(server) || !(server instanceof NettyServer)) {
return;
}
val nettyServer = (NettyServer) server;
val executor = (StandardThreadExecutor) ReflectionUtil.getFieldValue(NettyServer.class, EXECUTOR_FIELD, nettyServer);
if (Objects.nonNull(executor)) {
StandardThreadExecutorProxy proxy = new StandardThreadExecutorProxy(executor);
String tpName = TP_PREFIX + "#" + nettyServer.getUrl().getPort();
try {
ReflectionUtil.setFieldValue(EXECUTOR_FIELD, nettyServer, proxy);
putAndFinalize(tpName, executor, proxy);
} catch (IllegalAccessException ex) {
log.error("DynamicTp adapter, enhance {} failed.", tpName, ex);
}
}
});
});
| 163
| 426
| 589
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-okhttp3/src/main/java/org/dromara/dynamictp/adapter/okhttp3/Okhttp3DtpAdapter.java
|
Okhttp3DtpAdapter
|
initialize
|
class Okhttp3DtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "okhttp3Tp";
private static final String EXECUTOR_SERVICE_FIELD = "executorService";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getOkhttp3Tp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
private String genTpName(String clientName) {
return TP_PREFIX + "#" + clientName;
}
}
|
super.initialize();
val beans = ApplicationContextHolder.getBeansOfType(OkHttpClient.class);
if (MapUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type OkHttpClient.");
return;
}
beans.forEach((k, v) -> {
val executor = v.dispatcher().executorService();
if (executor instanceof ThreadPoolExecutor) {
enhanceOriginExecutor(genTpName(k), (ThreadPoolExecutor) executor, EXECUTOR_SERVICE_FIELD, v.dispatcher());
}
});
| 187
| 147
| 334
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-rabbitmq/src/main/java/org/dromara/dynamictp/adapter/rabbitmq/RabbitMqDtpAdapter.java
|
RabbitMqDtpAdapter
|
initialize
|
class RabbitMqDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "rabbitMqTp";
private static final String CONSUME_EXECUTOR_FIELD = "executorService";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getRabbitmqTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
private String genTpName(String beanName) {
return TP_PREFIX + "#" + beanName;
}
}
|
super.initialize();
val beans = ApplicationContextHolder.getBeansOfType(AbstractConnectionFactory.class);
if (MapUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type AbstractConnectionFactory.");
return;
}
beans.forEach((k, v) -> {
AbstractConnectionFactory connFactory = (AbstractConnectionFactory) v;
ExecutorService executor = (ExecutorService) ReflectionUtil.getFieldValue(
AbstractConnectionFactory.class, CONSUME_EXECUTOR_FIELD, connFactory);
if (Objects.nonNull(executor) && executor instanceof ThreadPoolExecutor) {
String tpName = genTpName(k);
enhanceOriginExecutor(tpName, (ThreadPoolExecutor) executor, CONSUME_EXECUTOR_FIELD, connFactory);
}
});
| 193
| 210
| 403
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-rocketmq/src/main/java/org/dromara/dynamictp/adapter/rocketmq/AliyunOnsRocketMqAdapter.java
|
AliyunOnsRocketMqAdapter
|
accept
|
class AliyunOnsRocketMqAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "rocketMqTp";
private static final String CONSUME_EXECUTOR_FIELD = "consumeExecutor";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getRocketMqTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {
super.initialize();
adaptConsumerExecutors();
}
private void adaptConsumerExecutors() {
// get consumer beans
val beans = ApplicationContextHolder.getBeansOfType(Consumer.class);
if (MapUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type Consumer.");
return;
}
beans.forEach(this::accept);
}
private void accept(String k, Consumer v) {<FILL_FUNCTION_BODY>}
}
|
val consumer = (ConsumerImpl) v;
val defaultMqPushConsumer = (DefaultMQPushConsumer) ReflectionUtil.getFieldValue(
ConsumerImpl.class, "defaultMQPushConsumer", consumer);
if (Objects.isNull(defaultMqPushConsumer)) {
return;
}
val impl = (DefaultMQPushConsumerImpl) ReflectionUtil.getFieldValue(
DefaultMQPushConsumer.class, "defaultMQPushConsumerImpl", defaultMqPushConsumer);
if (Objects.isNull(impl)) {
return;
}
val consumeMessageService = impl.getConsumeMessageService();
String tpName = defaultMqPushConsumer.getConsumerGroup();
if (consumeMessageService instanceof ConsumeMessageConcurrentlyService) {
tpName = TP_PREFIX + "#consumer#concurrently#" + tpName;
} else if (consumeMessageService instanceof ConsumeMessageOrderlyService) {
tpName = TP_PREFIX + "#consumer#orderly#" + tpName;
}
ThreadPoolExecutor executor = (ThreadPoolExecutor) ReflectionUtil.getFieldValue(CONSUME_EXECUTOR_FIELD, consumeMessageService);
if (Objects.nonNull(executor)) {
enhanceOriginExecutor(tpName, executor, CONSUME_EXECUTOR_FIELD, consumeMessageService);
}
| 276
| 356
| 632
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-rocketmq/src/main/java/org/dromara/dynamictp/adapter/rocketmq/RocketMqDtpAdapter.java
|
RocketMqDtpAdapter
|
adaptProducerExecutors
|
class RocketMqDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "rocketMqTp";
private static final String CONSUME_EXECUTOR_FIELD = "consumeExecutor";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getRocketMqTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {
super.initialize();
adaptConsumerExecutors();
adaptProducerExecutors();
}
public void adaptConsumerExecutors() {
val beans = JVMTI.getInstances(DefaultMQPushConsumer.class);
if (CollectionUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type DefaultMQPushConsumer.");
return;
}
for (DefaultMQPushConsumer consumer : beans) {
val pushConsumer = (DefaultMQPushConsumerImpl) ReflectionUtil.getFieldValue(DefaultMQPushConsumer.class,
"defaultMQPushConsumerImpl", consumer);
if (Objects.isNull(pushConsumer)) {
continue;
}
val consumeMessageService = pushConsumer.getConsumeMessageService();
ThreadPoolExecutor executor = (ThreadPoolExecutor) ReflectionUtil.getFieldValue(CONSUME_EXECUTOR_FIELD, consumeMessageService);
if (Objects.nonNull(executor)) {
String tpName = consumer.getConsumerGroup();
if (consumeMessageService instanceof ConsumeMessageConcurrentlyService) {
tpName = TP_PREFIX + "#consumer#concurrently#" + tpName;
} else if (consumeMessageService instanceof ConsumeMessageOrderlyService) {
tpName = TP_PREFIX + "#consumer#orderly#" + tpName;
}
enhanceOriginExecutor(tpName, executor, CONSUME_EXECUTOR_FIELD, consumeMessageService);
}
}
}
public void adaptProducerExecutors() {<FILL_FUNCTION_BODY>}
}
|
val beans = JVMTI.getInstances(DefaultMQProducer.class);
if (CollectionUtils.isEmpty(beans)) {
log.warn("Cannot find beans of type DefaultMQProducer.");
return;
}
for (DefaultMQProducer defaultMQProducer : beans) {
if (Objects.isNull(ReflectionUtils.findMethod(DefaultMQProducerImpl.class, "getAsyncSenderExecutor"))) {
continue;
}
val producer = (DefaultMQProducerImpl) ReflectionUtil.getFieldValue(DefaultMQProducer.class,
"defaultMQProducerImpl", defaultMQProducer);
if (Objects.isNull(producer)) {
continue;
}
ThreadPoolExecutor executor = (ThreadPoolExecutor) producer.getAsyncSenderExecutor();
if (Objects.nonNull(executor)) {
ThreadPoolExecutorProxy proxy = new ThreadPoolExecutorProxy(executor);
producer.setAsyncSenderExecutor(proxy);
String proKey = TP_PREFIX + "#producer#" + defaultMQProducer.getProducerGroup();
putAndFinalize(proKey, executor, proxy);
}
}
| 554
| 298
| 852
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-sofa/src/main/java/org/dromara/dynamictp/adapter/sofa/SofaDtpAdapter.java
|
SofaDtpAdapter
|
initialize
|
class SofaDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "sofaTp";
private static final String SERVER_CONFIG_FIELD = "serverConfig";
private static final String USER_THREAD_FIELD = "userThreadMap";
private static final String USER_THREAD_EXECUTOR_FIELD = "executor";
private static final String BIZ_THREAD_POOL = "bizThreadPool";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getSofaTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
private void handleUserThreadPools() {
try {
Field f = UserThreadPoolManager.class.getDeclaredField(USER_THREAD_FIELD);
f.setAccessible(true);
val userThreadMap = (Map<String, UserThreadPool>) f.get(null);
if (MapUtils.isNotEmpty(userThreadMap)) {
userThreadMap.forEach((k, v) -> {
String tpName = TP_PREFIX + "#" + k;
enhanceOriginExecutor(tpName, v.getExecutor(), USER_THREAD_FIELD, v);
});
}
} catch (Exception e) {
log.warn("UserThreadPoolManager handles failed", e);
}
}
}
|
super.initialize();
List<Server> servers = ServerFactory.getServers();
boolean hasUserThread = UserThreadPoolManager.hasUserThread();
if (CollectionUtils.isEmpty(servers) && !hasUserThread) {
log.warn("Empty servers and empty user thread pools.");
return;
}
servers.forEach(v -> {
ThreadPoolExecutor executor = null;
ServerConfig serverConfig = null;
if (v instanceof BoltServer) {
BoltServer server = (BoltServer) v;
executor = server.getBizThreadPool();
serverConfig = (ServerConfig) ReflectionUtil.getFieldValue(BoltServer.class,
SERVER_CONFIG_FIELD, server);
} else if (v instanceof AbstractHttpServer) {
AbstractHttpServer server = (AbstractHttpServer) v;
executor = server.getBizThreadPool();
serverConfig = (ServerConfig) ReflectionUtil.getFieldValue(AbstractHttpServer.class,
SERVER_CONFIG_FIELD, server);
}
if (Objects.isNull(executor) || Objects.isNull(serverConfig)) {
return;
}
String tpName = TP_PREFIX + "#" + serverConfig.getProtocol() + "#" + serverConfig.getPort();
enhanceOriginExecutor(tpName, executor, BIZ_THREAD_POOL, v);
});
if (hasUserThread) {
handleUserThreadPools();
}
| 397
| 370
| 767
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/adapter/adapter-tars/src/main/java/org/dromara/dynamictp/adapter/tars/TarsDtpAdapter.java
|
TarsDtpAdapter
|
initialize
|
class TarsDtpAdapter extends AbstractDtpAdapter {
private static final String TP_PREFIX = "tarsTp";
private static final String COMMUNICATORS_FIELD = "CommunicatorMap";
private static final String THREAD_POOL_FIELD = "threadPoolExecutor";
private static final String COMMUNICATOR_ID_FIELD = "id";
@Override
public void refresh(DtpProperties dtpProperties) {
refresh(dtpProperties.getTarsTp(), dtpProperties.getPlatforms());
}
@Override
protected String getTpPrefix() {
return TP_PREFIX;
}
@Override
protected void initialize() {<FILL_FUNCTION_BODY>}
}
|
super.initialize();
CommunicatorFactory communicatorFactory = CommunicatorFactory.getInstance();
val communicatorMap = (ConcurrentHashMap<Object, Communicator>) ReflectionUtil.getFieldValue(
CommunicatorFactory.class, COMMUNICATORS_FIELD, communicatorFactory);
if (MapUtils.isEmpty(communicatorMap)) {
log.warn("Cannot find instances of type Communicator.");
return;
}
communicatorMap.forEach((k, v) -> {
val executor = (ThreadPoolExecutor) ReflectionUtil.getFieldValue(Communicator.class, THREAD_POOL_FIELD, v);
if (Objects.isNull(executor)) {
return;
}
val tpName = TP_PREFIX + "#" + ReflectionUtil.getFieldValue(Communicator.class, COMMUNICATOR_ID_FIELD, v);
enhanceOriginExecutor(tpName, executor, THREAD_POOL_FIELD, v);
});
| 191
| 246
| 437
|
<methods>public non-sealed void <init>() ,public Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> getExecutorWrappers() ,public List<org.dromara.dynamictp.common.entity.ThreadPoolStats> getMultiPoolStats() ,public void refresh(List<org.dromara.dynamictp.common.entity.TpExecutorProps>, List<org.dromara.dynamictp.common.entity.NotifyPlatform>) ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, List<org.dromara.dynamictp.common.entity.NotifyPlatform>, org.dromara.dynamictp.common.entity.TpExecutorProps) <variables>private static final Equator EQUATOR,protected final Map<java.lang.String,org.dromara.dynamictp.core.support.ExecutorWrapper> executors
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/entity/DtpExecutorProps.java
|
DtpExecutorProps
|
coreParamIsInValid
|
class DtpExecutorProps extends TpExecutorProps {
/**
* Executor type, used in create phase, see {@link org.dromara.dynamictp.core.executor.ExecutorType}
*/
private String executorType;
/**
* Blocking queue type, see {@link QueueTypeEnum}
*/
private String queueType = QueueTypeEnum.VARIABLE_LINKED_BLOCKING_QUEUE.getName();
/**
* BlockingQueue capacity.
*/
private int queueCapacity = 1024;
/**
* If fair strategy, for SynchronousQueue
*/
private boolean fair = false;
/**
* Max free memory for MemorySafeLBQ, unit M
*/
private int maxFreeMemory = 16;
/**
* RejectedExecutionHandler type, see {@link RejectedTypeEnum}
*/
private String rejectedHandlerType = RejectedTypeEnum.ABORT_POLICY.getName();
/**
* If allow core thread timeout.
*/
private boolean allowCoreThreadTimeOut = false;
/**
* Thread name prefix.
*/
private String threadNamePrefix = "dtp";
/**
* Whether to wait for scheduled tasks to complete on shutdown,
* not interrupting running tasks and executing all tasks in the queue.
*/
private boolean waitForTasksToCompleteOnShutdown = true;
/**
* The maximum number of seconds that this executor is supposed to block
* on shutdown in order to wait for remaining tasks to complete their execution
* before the rest of the container continues to shut down.
*/
private int awaitTerminationSeconds = 3;
/**
* If pre start all core threads.
*/
private boolean preStartAllCoreThreads = false;
/**
* If enhance reject.
*/
private boolean rejectEnhanced = true;
/**
* Plugin names.
*/
private Set<String> pluginNames;
/**
* check core param is inValid
*
* @return boolean return true means params is inValid
*/
public boolean coreParamIsInValid() {<FILL_FUNCTION_BODY>}
}
|
return this.getCorePoolSize() < 0
|| this.getMaximumPoolSize() <= 0
|| this.getMaximumPoolSize() < this.getCorePoolSize()
|| this.getKeepAliveTime() < 0;
| 556
| 61
| 617
|
<methods>public non-sealed void <init>() <variables>private List<java.lang.String> awareNames,private int corePoolSize,private long keepAliveTime,private int maximumPoolSize,private boolean notifyEnabled,private List<org.dromara.dynamictp.common.entity.NotifyItem> notifyItems,private List<java.lang.String> platformIds,private long queueTimeout,private long runTimeout,private Set<java.lang.String> taskWrapperNames,private java.lang.String threadPoolAliasName,private java.lang.String threadPoolName,private boolean tryInterrupt,private java.util.concurrent.TimeUnit unit
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/entity/NotifyItem.java
|
NotifyItem
|
getAllNotifyItems
|
class NotifyItem {
/**
* Notify platform id
*/
private List<String> platformIds;
/**
* If enabled notify.
*/
private boolean enabled = true;
/**
* Notify item, see {@link NotifyItemEnum}
*/
private String type;
/**
* Alarm threshold.
*/
private int threshold;
/**
* Alarm interval, time unit(s)
*/
private int interval = 120;
/**
* Cluster notify limit.
*/
private int clusterLimit = 1;
/**
* Receivers, split by, If NotifyPlatform.receivers have a value, they will be overwritten by the thread pool alarm
*/
private String receivers;
public static List<NotifyItem> mergeAllNotifyItems(List<NotifyItem> source) {
// update notify items
if (CollectionUtils.isEmpty(source)) {
return getAllNotifyItems();
} else {
val configuredTypes = source.stream().map(NotifyItem::getType).collect(toList());
val defaultItems = getAllNotifyItems().stream()
.filter(t -> !StringUtil.containsIgnoreCase(t.getType(), configuredTypes))
.collect(Collectors.toList());
source.addAll(defaultItems);
return source;
}
}
public static List<NotifyItem> getAllNotifyItems() {<FILL_FUNCTION_BODY>}
public static List<NotifyItem> getSimpleNotifyItems() {
NotifyItem changeNotify = new NotifyItem();
changeNotify.setType(NotifyItemEnum.CHANGE.getValue());
changeNotify.setInterval(1);
NotifyItem livenessNotify = new NotifyItem();
livenessNotify.setType(NotifyItemEnum.LIVENESS.getValue());
livenessNotify.setThreshold(70);
NotifyItem capacityNotify = new NotifyItem();
capacityNotify.setType(NotifyItemEnum.CAPACITY.getValue());
capacityNotify.setThreshold(70);
List<NotifyItem> notifyItems = new ArrayList<>(3);
notifyItems.add(livenessNotify);
notifyItems.add(changeNotify);
notifyItems.add(capacityNotify);
return notifyItems;
}
}
|
NotifyItem rejectNotify = new NotifyItem();
rejectNotify.setType(NotifyItemEnum.REJECT.getValue());
rejectNotify.setThreshold(10);
NotifyItem runTimeoutNotify = new NotifyItem();
runTimeoutNotify.setType(NotifyItemEnum.RUN_TIMEOUT.getValue());
runTimeoutNotify.setThreshold(10);
NotifyItem queueTimeoutNotify = new NotifyItem();
queueTimeoutNotify.setType(NotifyItemEnum.QUEUE_TIMEOUT.getValue());
queueTimeoutNotify.setThreshold(10);
List<NotifyItem> notifyItems = new ArrayList<>(6);
notifyItems.addAll(getSimpleNotifyItems());
notifyItems.add(rejectNotify);
notifyItems.add(runTimeoutNotify);
notifyItems.add(queueTimeoutNotify);
return notifyItems;
| 611
| 229
| 840
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/notifier/AbstractHttpNotifier.java
|
AbstractHttpNotifier
|
send0
|
class AbstractHttpNotifier extends AbstractNotifier {
@Override
protected void send0(NotifyPlatform platform, String content) {<FILL_FUNCTION_BODY>}
/**
* build http message body
* @param platform platform
* @param content content
* @return java.lang.String
*/
protected abstract String buildMsgBody(NotifyPlatform platform, String content);
/**
* build http url
* @param platform platform
* @return java.lang.String
*/
protected abstract String buildUrl(NotifyPlatform platform);
}
|
val url = buildUrl(platform);
val msgBody = buildMsgBody(platform, content);
HttpRequest request = HttpRequest.post(url)
.setConnectionTimeout(platform.getTimeout())
.setReadTimeout(platform.getTimeout())
.body(msgBody);
HttpResponse response = request.execute();
if (Objects.nonNull(response)) {
log.info("DynamicTp notify, {} send success, response: {}, request: {}",
platform(), response.body(), msgBody);
}
| 145
| 130
| 275
|
<methods>public non-sealed void <init>() ,public final void send(org.dromara.dynamictp.common.entity.NotifyPlatform, java.lang.String) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/notifier/AbstractNotifier.java
|
AbstractNotifier
|
send
|
class AbstractNotifier implements Notifier {
@Override
public final void send(NotifyPlatform platform, String content) {<FILL_FUNCTION_BODY>}
/**
* Send message.
*
* @param platform platform
* @param content content
*/
protected abstract void send0(NotifyPlatform platform, String content);
}
|
try {
send0(platform, content);
} catch (Exception e) {
log.error("DynamicTp notify, {} send failed.", platform(), e);
}
| 90
| 47
| 137
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/notifier/DingNotifier.java
|
DingNotifier
|
buildMsgBody
|
class DingNotifier extends AbstractHttpNotifier {
private static final String ALL = "all";
@Override
public String platform() {
return NotifyPlatformEnum.DING.name().toLowerCase();
}
@Override
protected String buildMsgBody(NotifyPlatform platform, String content) {<FILL_FUNCTION_BODY>}
@Override
protected String buildUrl(NotifyPlatform platform) {
String webhook = Optional.ofNullable(platform.getWebhook()).orElse(DingNotifyConst.DING_WEBHOOK);
return getTargetUrl(platform.getSecret(), platform.getUrlKey(), webhook);
}
/**
* Build target url.
*
* @param secret secret
* @param accessToken accessToken
* @param webhook webhook
* @return url
*/
private String getTargetUrl(String secret, String accessToken, String webhook) {
UrlBuilder builder = UrlBuilder.of(webhook);
if (StringUtils.isNotBlank(accessToken) && StringUtils.isBlank(builder.getQuery().get(DingNotifyConst.ACCESS_TOKEN_PARAM))) {
builder.addQuery(DingNotifyConst.ACCESS_TOKEN_PARAM, accessToken);
}
if (StringUtils.isNotBlank(secret)) {
long timestamp = System.currentTimeMillis();
builder.addQuery(DingNotifyConst.TIMESTAMP_PARAM, timestamp);
builder.addQuery(DingNotifyConst.SIGN_PARAM, DingSignUtil.dingSign(secret, timestamp));
}
return builder.build();
}
}
|
MarkdownReq.Markdown markdown = new MarkdownReq.Markdown();
markdown.setTitle(DING_NOTICE_TITLE);
markdown.setText(content);
MarkdownReq.At at = new MarkdownReq.At();
List<String> mobiles = Lists.newArrayList(platform.getReceivers().split(","));
at.setAtMobiles(mobiles);
if (mobiles.contains(ALL) || CollectionUtils.isEmpty(mobiles)) {
at.setAtAll(true);
}
MarkdownReq markdownReq = new MarkdownReq();
markdownReq.setMsgtype("markdown");
markdownReq.setMarkdown(markdown);
markdownReq.setAt(at);
return JsonUtil.toJson(markdownReq);
| 420
| 219
| 639
|
<methods>public non-sealed void <init>() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/notifier/LarkNotifier.java
|
LarkNotifier
|
buildMsgBody
|
class LarkNotifier extends AbstractHttpNotifier {
/**
* LF
*/
public static final String LF = "\n";
/**
* HmacSHA256 encryption algorithm
*/
public static final String HMAC_SHA_256 = "HmacSHA256";
@Override
public String platform() {
return NotifyPlatformEnum.LARK.name().toLowerCase();
}
/**
* get signature
*
* @param secret secret
* @param timestamp timestamp
* @return signature
* @throws NoSuchAlgorithmException Mac.getInstance("HmacSHA256")
* @throws InvalidKeyException mac.init(java.security.Key)
*/
protected String genSign(String secret, Long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
String stringToSign = timestamp + LF + secret;
Mac mac = Mac.getInstance(HMAC_SHA_256);
mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), HMAC_SHA_256));
byte[] signData = mac.doFinal(new byte[]{});
return new String(Base64.encodeBase64(signData));
}
@Override
protected String buildMsgBody(NotifyPlatform platform, String content) {<FILL_FUNCTION_BODY>}
@Override
protected String buildUrl(NotifyPlatform platform) {
if (StringUtils.isBlank(platform.getUrlKey())) {
return platform.getWebhook();
}
UrlBuilder builder = UrlBuilder.of(Optional.ofNullable(platform.getWebhook()).orElse(LarkNotifyConst.LARK_WEBHOOK));
List<String> segments = builder.getPath().getSegments();
if (!Objects.equals(platform.getUrlKey(), segments.get(segments.size() - 1))) {
builder.addPath(platform.getUrlKey());
}
return builder.build();
}
}
|
if (StringUtils.isBlank(platform.getSecret())) {
return content;
}
try {
val secondsTimestamp = System.currentTimeMillis() / 1000;
val sign = genSign(platform.getSecret(), secondsTimestamp);
content = content.replaceFirst(SIGN_REPLACE, String.format(SIGN_PARAM_PREFIX, secondsTimestamp, sign));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
log.error("DynamicTp notify, lark generate signature failed...", e);
}
return content;
| 518
| 146
| 664
|
<methods>public non-sealed void <init>() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/notifier/WechatNotifier.java
|
WechatNotifier
|
buildMsgBody
|
class WechatNotifier extends AbstractHttpNotifier {
@Override
public String platform() {
return NotifyPlatformEnum.WECHAT.name().toLowerCase();
}
@Override
protected String buildMsgBody(NotifyPlatform platform, String content) {<FILL_FUNCTION_BODY>}
@Override
protected String buildUrl(NotifyPlatform platform) {
if (StringUtils.isBlank(platform.getUrlKey())) {
return platform.getWebhook();
}
UrlBuilder builder = UrlBuilder.of(Optional.ofNullable(platform.getWebhook()).orElse(WechatNotifyConst.WECHAT_WEB_HOOK));
if (StringUtils.isBlank(builder.getQuery().get(WechatNotifyConst.KEY_PARAM))) {
builder.addQuery(WechatNotifyConst.KEY_PARAM, platform.getUrlKey());
}
return builder.build();
}
}
|
MarkdownReq markdownReq = new MarkdownReq();
markdownReq.setMsgtype("markdown");
MarkdownReq.Markdown markdown = new MarkdownReq.Markdown();
markdown.setContent(content);
markdownReq.setMarkdown(markdown);
return JsonUtil.toJson(markdownReq);
| 238
| 93
| 331
|
<methods>public non-sealed void <init>() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/config/JsonConfigParser.java
|
JsonConfigParser
|
doParse
|
class JsonConfigParser extends AbstractConfigParser {
private static final List<ConfigFileTypeEnum> CONFIG_TYPES = Lists.newArrayList(ConfigFileTypeEnum.JSON);
private static final ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper();
}
@Override
public List<ConfigFileTypeEnum> types() {
return CONFIG_TYPES;
}
@Override
public Map<Object, Object> doParse(String content) throws IOException {
if (StringUtils.isEmpty(content)) {
return Collections.emptyMap();
}
return doParse(content, MAIN_PROPERTIES_PREFIX);
}
@Override
public Map<Object, Object> doParse(String content, String prefix) throws IOException {<FILL_FUNCTION_BODY>}
private void flatMap(Map<Object, Object> result, Map<String, Object> dataMap, String prefix) {
if (MapUtils.isEmpty(dataMap)) {
return;
}
dataMap.forEach((k, v) -> {
String fullKey = genFullKey(prefix, k);
if (v instanceof Map) {
flatMap(result, (Map<String, Object>) v, fullKey);
return;
} else if (v instanceof Collection) {
int count = 0;
for (Object obj : (Collection<Object>) v) {
String kk = ARR_LEFT_BRACKET + (count++) + ARR_RIGHT_BRACKET;
flatMap(result, Collections.singletonMap(kk, obj), fullKey);
}
return;
}
result.put(fullKey, v);
});
}
private String genFullKey(String prefix, String key) {
if (StringUtils.isEmpty(prefix)) {
return key;
}
return key.startsWith(ARR_LEFT_BRACKET) ? prefix.concat(key) : prefix.concat(DOT).concat(key);
}
}
|
Map<String, Object> originMap = MAPPER.readValue(content, LinkedHashMap.class);
Map<Object, Object> result = Maps.newHashMap();
flatMap(result, originMap, prefix);
return result;
| 515
| 65
| 580
|
<methods>public non-sealed void <init>() ,public Map<java.lang.Object,java.lang.Object> doParse(java.lang.String, java.lang.String) throws java.io.IOException,public boolean supports(org.dromara.dynamictp.common.em.ConfigFileTypeEnum) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/config/PropertiesConfigParser.java
|
PropertiesConfigParser
|
doParse
|
class PropertiesConfigParser extends AbstractConfigParser {
private static final List<ConfigFileTypeEnum> CONFIG_TYPES = Lists.newArrayList(ConfigFileTypeEnum.PROPERTIES);
@Override
public List<ConfigFileTypeEnum> types() {
return CONFIG_TYPES;
}
@Override
public Map<Object, Object> doParse(String content) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isBlank(content)) {
return Collections.emptyMap();
}
Properties properties = new Properties();
properties.load(new StringReader(content));
return properties;
| 113
| 55
| 168
|
<methods>public non-sealed void <init>() ,public Map<java.lang.Object,java.lang.Object> doParse(java.lang.String, java.lang.String) throws java.io.IOException,public boolean supports(org.dromara.dynamictp.common.em.ConfigFileTypeEnum) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/config/YamlConfigParser.java
|
YamlConfigParser
|
doParse
|
class YamlConfigParser extends AbstractConfigParser {
private static final List<ConfigFileTypeEnum> CONFIG_TYPES = Lists.newArrayList(
ConfigFileTypeEnum.YML, ConfigFileTypeEnum.YAML);
@Override
public List<ConfigFileTypeEnum> types() {
return CONFIG_TYPES;
}
@Override
public Map<Object, Object> doParse(String content) {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isEmpty(content)) {
return Collections.emptyMap();
}
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(new ByteArrayResource(content.getBytes()));
return bean.getObject();
| 122
| 69
| 191
|
<methods>public non-sealed void <init>() ,public Map<java.lang.Object,java.lang.Object> doParse(java.lang.String, java.lang.String) throws java.io.IOException,public boolean supports(org.dromara.dynamictp.common.em.ConfigFileTypeEnum) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/json/AbstractJsonParser.java
|
AbstractJsonParser
|
supports
|
class AbstractJsonParser implements JsonParser {
@Override
public boolean supports() {<FILL_FUNCTION_BODY>}
/**
* get mapper class name
*
* @return mapper class name
*/
protected abstract String getMapperClassName();
}
|
try {
Class.forName(getMapperClassName());
return true;
} catch (ClassNotFoundException e) {
return false;
}
| 72
| 43
| 115
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/json/GsonParser.java
|
GsonParser
|
getMapper
|
class GsonParser extends AbstractJsonParser {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String PACKAGE_NAME = "com.google.gson.Gson";
private volatile Gson mapper;
@Override
public <T> T fromJson(String json, Type typeOfT) {
return getMapper().fromJson(json, typeOfT);
}
@Override
public String toJson(Object obj) {
return getMapper().toJson(obj);
}
private Gson getMapper() {<FILL_FUNCTION_BODY>}
protected Gson createMapper() {
TypeAdapter<LocalDateTime> timeTypeAdapter = new TypeAdapter<LocalDateTime>() {
@Override
public void write(JsonWriter out, LocalDateTime value) throws IOException {
if (Objects.nonNull(value)) {
out.value(value.format(DateTimeFormatter.ofPattern(DATE_FORMAT)));
} else {
out.nullValue();
}
}
@Override
public LocalDateTime read(JsonReader in) throws IOException {
final JsonToken token = in.peek();
if (token == JsonToken.NULL) {
return null;
} else {
return LocalDateTime.parse(in.nextString(), DateTimeFormatter.ofPattern(DATE_FORMAT));
}
}
};
return new GsonBuilder()
.setDateFormat(DATE_FORMAT)
.registerTypeAdapter(LocalDateTime.class, timeTypeAdapter)
.create();
}
@Override
protected String getMapperClassName() {
return PACKAGE_NAME;
}
}
|
if (mapper == null) {
synchronized (this) {
if (mapper == null) {
mapper = createMapper();
}
}
}
return mapper;
| 426
| 54
| 480
|
<methods>public non-sealed void <init>() ,public boolean supports() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/parser/json/JacksonParser.java
|
JacksonParser
|
toJson
|
class JacksonParser extends AbstractJsonParser {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String PACKAGE_NAME = "com.fasterxml.jackson.databind.ObjectMapper";
private volatile ObjectMapper mapper;
@Override
public <T> T fromJson(String json, Type typeOfT) {
try {
final ObjectMapper objectMapper = getMapper();
return objectMapper.readValue(json, objectMapper.constructType(typeOfT));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toJson(Object obj) {<FILL_FUNCTION_BODY>}
private ObjectMapper getMapper() {
// double check lock
if (mapper == null) {
synchronized (this) {
if (mapper == null) {
mapper = createMapper();
}
}
}
return mapper;
}
protected ObjectMapper createMapper() {
// 只提供最简单的方案
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
return JsonMapper.builder()
.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true)
// 反序列化时,遇到未知属性会不会报错 true - 遇到没有的属性就报错 false - 没有的属性不会管,不会报错
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// 如果是空对象的时候,不抛异常
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
// 序列化的时候序列对象的那些属性
.serializationInclusion(JsonInclude.Include.NON_EMPTY)
.addModules(javaTimeModule)
.addModules(new JavaTimeModule())
// 修改序列化后日期格式
.defaultDateFormat(new SimpleDateFormat(DATE_FORMAT))
.build();
}
@Override
protected String getMapperClassName() {
return PACKAGE_NAME;
}
}
|
try {
return getMapper().writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e.getMessage());
}
| 634
| 46
| 680
|
<methods>public non-sealed void <init>() ,public boolean supports() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/pattern/filter/InvokerChainFactory.java
|
InvokerChainFactory
|
buildInvokerChain
|
class InvokerChainFactory {
private InvokerChainFactory() { }
@SafeVarargs
public static<T> InvokerChain<T> buildInvokerChain(Invoker<T> target, Filter<T>... filters) {<FILL_FUNCTION_BODY>}
}
|
InvokerChain<T> invokerChain = new InvokerChain<>();
Invoker<T> last = target;
for (int i = filters.length - 1; i >= 0; i--) {
Invoker<T> next = last;
Filter<T> filter = filters[i];
last = context -> filter.doFilter(context, next);
}
invokerChain.setHead(last);
return invokerChain;
| 72
| 115
| 187
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/plugin/DtpInterceptorProxy.java
|
DtpInterceptorProxy
|
intercept
|
class DtpInterceptorProxy implements MethodInterceptor {
private final Object target;
private final DtpInterceptor interceptor;
private final Map<Class<?>, Set<Method>> signatureMap;
public DtpInterceptorProxy(Object target, DtpInterceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (CollectionUtils.isNotEmpty(methods) && methods.contains(method)) {
return interceptor.intercept(new DtpInvocation(target, method, args));
}
return method.invoke(target, args);
| 172
| 81
| 253
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/plugin/DtpInterceptorProxyFactory.java
|
DtpInterceptorProxyFactory
|
enhance
|
class DtpInterceptorProxyFactory {
private DtpInterceptorProxyFactory() { }
public static Object enhance(Object target, DtpInterceptor interceptor) {
return enhance(target, null, null, interceptor);
}
public static Object enhance(Object target, Class<?>[] argumentTypes, Object[] arguments, DtpInterceptor interceptor) {<FILL_FUNCTION_BODY>}
private static Map<Class<?>, Set<Method>> getSignatureMap(DtpInterceptor interceptor) {
DtpIntercepts interceptsAnno = interceptor.getClass().getAnnotation(DtpIntercepts.class);
if (interceptsAnno == null) {
throw new PluginException("No @DtpIntercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
DtpSignature[] signatures = interceptsAnno.signatures();
Map<Class<?>, Set<Method>> signatureMap = Maps.newHashMap();
for (DtpSignature signature : signatures) {
Set<Method> methods = signatureMap.computeIfAbsent(signature.clazz(), k -> new HashSet<>());
try {
Method method = signature.clazz().getMethod(signature.method(), signature.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + signature.clazz() + " named " + signature.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
}
|
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
if (!signatureMap.containsKey(target.getClass())) {
return target;
}
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(new DtpInterceptorProxy(target, interceptor, signatureMap));
if (Objects.isNull(argumentTypes) || Objects.isNull(arguments)) {
return enhancer.create();
}
return enhancer.create(argumentTypes, arguments);
| 402
| 149
| 551
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/plugin/DtpInterceptorRegistry.java
|
DtpInterceptorRegistry
|
plugin
|
class DtpInterceptorRegistry {
/**
* Maintain all automatically registered and manually registered INTERCEPTORS
*/
private static final Map<String, DtpInterceptor> INTERCEPTORS = Maps.newConcurrentMap();
static {
List<DtpInterceptor> loadedInterceptors = ExtensionServiceLoader.get(DtpInterceptor.class);
if (CollectionUtils.isNotEmpty(loadedInterceptors)) {
loadedInterceptors.forEach(x -> {
DtpIntercepts interceptsAnno = x.getClass().getAnnotation(DtpIntercepts.class);
if (Objects.nonNull(interceptsAnno)) {
String name = StringUtils.isBlank(interceptsAnno.name()) ? x.getClass().getSimpleName() : interceptsAnno.name();
INTERCEPTORS.put(name, x);
}
});
}
}
private DtpInterceptorRegistry() { }
public static void register(String name, DtpInterceptor dtpInterceptor) {
log.info("DynamicTp register DtpInterceptor, name: {}, interceptor: {}", name, dtpInterceptor);
INTERCEPTORS.put(name, dtpInterceptor);
}
public static Map<String, DtpInterceptor> getInterceptors() {
return Collections.unmodifiableMap(INTERCEPTORS);
}
public static Object pluginAll(Object target) {
return plugin(target, INTERCEPTORS.keySet());
}
public static Object pluginAll(Object target, Class<?>[] argTypes, Object[] args) {
return plugin(target, INTERCEPTORS.keySet(), argTypes, args);
}
public static Object plugin(Object target, Set<String> interceptors) {<FILL_FUNCTION_BODY>}
public static Object plugin(Object target, Set<String> interceptors, Class<?>[] argTypes, Object[] args) {
val filterInterceptors = getInterceptors(interceptors);
for (DtpInterceptor interceptor : filterInterceptors) {
target = interceptor.plugin(target, argTypes, args);
}
return target;
}
private static Collection<DtpInterceptor> getInterceptors(Set<String> interceptors) {
if (CollectionUtils.isEmpty(interceptors)) {
return INTERCEPTORS.values();
}
return INTERCEPTORS.entrySet()
.stream()
.filter(x -> StringUtil.containsIgnoreCase(x.getKey(), interceptors))
.map(Map.Entry::getValue)
.collect(toList());
}
}
|
val filterInterceptors = getInterceptors(interceptors);
for (DtpInterceptor interceptor : filterInterceptors) {
target = interceptor.plugin(target);
}
return target;
| 685
| 59
| 744
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/queue/MemorySafeLinkedBlockingQueue.java
|
MemorySafeLinkedBlockingQueue
|
hasRemainedMemory
|
class MemorySafeLinkedBlockingQueue<E> extends VariableLinkedBlockingQueue<E> {
private static final long serialVersionUID = 8032578371739960142L;
public static final int THE_16_MB = 16 * 1024 * 1024;
private int maxFreeMemory;
public MemorySafeLinkedBlockingQueue() {
this(THE_16_MB);
}
public MemorySafeLinkedBlockingQueue(final int maxFreeMemory) {
super(Integer.MAX_VALUE);
this.maxFreeMemory = maxFreeMemory;
}
public MemorySafeLinkedBlockingQueue(final int capacity, final int maxFreeMemory) {
super(capacity);
this.maxFreeMemory = maxFreeMemory;
}
public MemorySafeLinkedBlockingQueue(final Collection<? extends E> c, final int maxFreeMemory) {
super(c);
this.maxFreeMemory = maxFreeMemory;
}
/**
* 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 int getMaxFreeMemory() {
return maxFreeMemory;
}
/**
* determine if there is any remaining free memory.
*
* @return true if has free memory
*/
public boolean hasRemainedMemory() {<FILL_FUNCTION_BODY>}
@Override
public void put(final E e) throws InterruptedException {
if (hasRemainedMemory()) {
super.put(e);
}
}
@Override
public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
return hasRemainedMemory() && super.offer(e, timeout, unit);
}
@Override
public boolean offer(final E e) {
return hasRemainedMemory() && super.offer(e);
}
}
|
if (MemoryLimitCalculator.maxAvailable() > maxFreeMemory) {
return true;
}
throw new RejectedExecutionException("No more memory can be used.");
| 557
| 45
| 602
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends E>) ,public void clear() ,public boolean contains(java.lang.Object) ,public int drainTo(Collection<? super E>) ,public int drainTo(Collection<? super E>, int) ,public Iterator<E> iterator() ,public boolean offer(E, long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public boolean offer(E) ,public E peek() ,public E poll(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public E poll() ,public void put(E) throws java.lang.InterruptedException,public int remainingCapacity() ,public boolean remove(java.lang.Object) ,public void setCapacity(int) ,public int size() ,public Spliterator<E> spliterator() ,public E take() throws java.lang.InterruptedException,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>private int capacity,private final java.util.concurrent.atomic.AtomicInteger count,transient Node<E> head,private transient Node<E> last,private final java.util.concurrent.locks.Condition notEmpty,private final java.util.concurrent.locks.Condition notFull,private final java.util.concurrent.locks.ReentrantLock putLock,private static final long serialVersionUID,private final java.util.concurrent.locks.ReentrantLock takeLock
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/queue/VariableLinkedBlockingQueue.java
|
LBQSpliterator
|
writeObject
|
class LBQSpliterator<E> implements Spliterator<E> {
static final int MAX_BATCH = 1 << 25; // max batch array size;
final VariableLinkedBlockingQueue<E> queue;
Node<E> current; // current node; null until initialized
int batch; // batch size for splits
boolean exhausted; // true when no more nodes
long est; // size estimate
LBQSpliterator(VariableLinkedBlockingQueue<E> queue) {
this.queue = queue;
this.est = queue.size();
}
@Override
public long estimateSize() {
return est;
}
@Override
public Spliterator<E> trySplit() {
Node<E> h;
final VariableLinkedBlockingQueue<E> q = this.queue;
int b = batch;
int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
if (!exhausted &&
((h = current) != null || (h = q.head.next) != null) &&
h.next != null) {
Object[] a = new Object[n];
int i = 0;
Node<E> p = current;
q.fullyLock();
try {
if (p != null || (p = q.head.next) != null) {
do {
if ((a[i] = p.item) != null) {
++i;
}
} while ((p = p.next) != null && i < n);
}
} finally {
q.fullyUnlock();
}
if ((current = p) == null) {
est = 0L;
exhausted = true;
} else if ((est -= i) < 0L) {
est = 0L;
}
if (i > 0) {
batch = i;
return Spliterators.spliterator(a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
Spliterator.CONCURRENT);
}
}
return null;
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
if (action == null) {
throw new NullPointerException();
}
final VariableLinkedBlockingQueue<E> q = this.queue;
if (!exhausted) {
exhausted = true;
Node<E> p = current;
do {
E e = null;
q.fullyLock();
try {
if (p == null) {
p = q.head.next;
}
while (p != null) {
e = p.item;
p = p.next;
if (e != null) {
break;
}
}
} finally {
q.fullyUnlock();
}
if (e != null) {
action.accept(e);
}
} while (p != null);
}
}
@Override
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null) {
throw new NullPointerException();
}
final VariableLinkedBlockingQueue<E> q = this.queue;
if (!exhausted) {
E e = null;
q.fullyLock();
try {
if (current == null) {
current = q.head.next;
}
while (current != null) {
e = current.item;
current = current.next;
if (e != null) {
break;
}
}
} finally {
q.fullyUnlock();
}
if (current == null) {
exhausted = true;
}
if (e != null) {
action.accept(e);
return true;
}
}
return false;
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.NONNULL |
Spliterator.CONCURRENT;
}
}
/**
* Returns a {@link Spliterator} over the elements in this queue.
*
* <p>The returned spliterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
*
* The {@code Spliterator} implements {@code trySplit} to permit limited
* parallelism.
*
* @return a {@code Spliterator} over the elements in this queue
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new LBQSpliterator<E>(this);
}
/**
* Saves this queue to a stream (that is, serializes it).
*
* @param s the stream
* @throws java.io.IOException if an I/O error occurs
* @serialData The capacity is emitted (int), followed by all of
* its elements (each an {@code Object}) in the proper order,
* followed by a null
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {<FILL_FUNCTION_BODY>
|
fullyLock();
try {
// Write out any hidden stuff, plus capacity
s.defaultWriteObject();
// Write out all elements in the proper order.
for (Node<E> p = head.next; p != null; p = p.next) {
s.writeObject(p.item);
}
// Use trailing null as sentinel
s.writeObject(null);
} finally {
fullyUnlock();
}
| 1,396
| 119
| 1,515
|
<methods>public boolean add(E) ,public boolean addAll(Collection<? extends E>) ,public void clear() ,public E element() ,public E remove() <variables>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/spring/ApplicationContextHolder.java
|
ApplicationContextHolder
|
getInstance
|
class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return getInstance().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getInstance().getBean(name, clazz);
}
public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
return getInstance().getBeansOfType(clazz);
}
public static ApplicationContext getInstance() {<FILL_FUNCTION_BODY>}
public static Environment getEnvironment() {
return getInstance().getEnvironment();
}
public static void publishEvent(ApplicationEvent event) {
getInstance().publishEvent(event);
}
}
|
if (Objects.isNull(context)) {
throw new NullPointerException("ApplicationContext is null, please check if the spring container is started.");
}
return context;
| 250
| 45
| 295
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/spring/OnceApplicationContextEventListener.java
|
OnceApplicationContextEventListener
|
onApplicationEvent
|
class OnceApplicationContextEventListener implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {
private ApplicationContext applicationContext;
protected OnceApplicationContextEventListener() { }
@Override
public void onApplicationEvent(ApplicationEvent event) {<FILL_FUNCTION_BODY>}
/**
* The subclass overrides this method to handle {@link ContextRefreshedEvent}
*
* @param event {@link ContextRefreshedEvent}
*/
protected void onContextRefreshedEvent(ContextRefreshedEvent event) {
}
/**
* The subclass overrides this method to handle {@link ContextStartedEvent}
*
* @param event {@link ContextStartedEvent}
*/
protected void onContextStartedEvent(ContextStartedEvent event) {
}
/**
* The subclass overrides this method to handle {@link ContextStoppedEvent}
*
* @param event {@link ContextStoppedEvent}
*/
protected void onContextStoppedEvent(ContextStoppedEvent event) {
}
/**
* The subclass overrides this method to handle {@link ContextClosedEvent}
*
* @param event {@link ContextClosedEvent}
*/
protected void onContextClosedEvent(ContextClosedEvent event) {
}
/**
* Is original {@link ApplicationContext} as the event source
* @param event {@link ApplicationEvent}
* @return if original, return <code>true</code>, or <code>false</code>
*/
private boolean isOriginalEventSource(ApplicationEvent event) {
return nullSafeEquals(this.applicationContext, event.getSource());
}
@Override
public final void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
if (isOriginalEventSource(event) && event instanceof ApplicationContextEvent) {
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextStartedEvent) {
onContextStartedEvent((ContextStartedEvent) event);
} else if (event instanceof ContextStoppedEvent) {
onContextStoppedEvent((ContextStoppedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
| 449
| 145
| 594
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/spring/SpringBeanHelper.java
|
SpringBeanHelper
|
doRegister
|
class SpringBeanHelper {
private SpringBeanHelper() { }
public static void register(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Map<String, Object> propertyValues,
Object... constructorArgs) {
register(registry, beanName, clazz, propertyValues, null, constructorArgs);
}
public static void register(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Map<String, Object> propertyValues,
List<String> dependsOnBeanNames,
Object... constructorArgs) {
if (ifPresent(registry, beanName, clazz) || registry.containsBeanDefinition(beanName)) {
log.info("DynamicTp registrar, bean [{}] already exists and will be overwritten", beanName);
registry.removeBeanDefinition(beanName);
}
doRegister(registry, beanName, clazz, propertyValues, dependsOnBeanNames, constructorArgs);
}
public static void registerIfAbsent(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Object... constructorArgs) {
registerIfAbsent(registry, beanName, clazz, null, null, constructorArgs);
}
public static void registerIfAbsent(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Map<String, Object> propertyValues,
Object... constructorArgs) {
registerIfAbsent(registry, beanName, clazz, propertyValues, null, constructorArgs);
}
public static void registerIfAbsent(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Map<String, Object> propertyValues,
List<String> dependsOnBeanNames,
Object... constructorArgs) {
if (!ifPresent(registry, beanName, clazz) && !registry.containsBeanDefinition(beanName)) {
doRegister(registry, beanName, clazz, propertyValues, dependsOnBeanNames, constructorArgs);
}
}
public static boolean ifPresent(BeanDefinitionRegistry registry, String beanName, Class<?> clazz) {
String[] beanNames = getBeanNames((ListableBeanFactory) registry, clazz);
return ArrayUtils.contains(beanNames, beanName);
}
public static String[] getBeanNames(ListableBeanFactory beanFactory, Class<?> clazz) {
return beanFactory.getBeanNamesForType(clazz, true, false);
}
private static void doRegister(BeanDefinitionRegistry registry,
String beanName,
Class<?> clazz,
Map<String, Object> propertyValues,
List<String> dependsOnBeanNames,
Object... constructorArgs) {<FILL_FUNCTION_BODY>}
}
|
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
for (Object constructorArg : constructorArgs) {
builder.addConstructorArgValue(constructorArg);
}
if (MapUtils.isNotEmpty(propertyValues)) {
propertyValues.forEach(builder::addPropertyValue);
}
if (CollectionUtils.isNotEmpty(dependsOnBeanNames)) {
dependsOnBeanNames.forEach(builder::addDependsOn);
}
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
| 689
| 135
| 824
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/CommonUtil.java
|
CommonUtil
|
getLocalHostExactAddress
|
class CommonUtil {
private CommonUtil() {
}
private static final ServiceInstance SERVICE_INSTANCE;
static {
Environment environment = ApplicationContextHolder.getEnvironment();
String appName = environment.getProperty("spring.application.name");
appName = StringUtils.isNoneBlank(appName) ? appName : "application";
String portStr = environment.getProperty("server.port");
int port = StringUtils.isNotBlank(portStr) ? Integer.parseInt(portStr) : 0;
String address = null;
try {
address = getLocalHostExactAddress().getHostAddress();
} catch (UnknownHostException | SocketException e) {
log.error("get localhost address error.", e);
}
String env = DtpProperties.getInstance().getEnv();
if (StringUtils.isBlank(env)) {
// fix #I8SSGQ
env = environment.getProperty("spring.profiles.active");
}
if (StringUtils.isBlank(env)) {
String[] profiles = environment.getActiveProfiles();
if (profiles.length < 1) {
profiles = environment.getDefaultProfiles();
}
if (profiles.length >= 1) {
env = profiles[0];
}
}
SERVICE_INSTANCE = new ServiceInstance(address, port, appName, env);
}
public static ServiceInstance getInstance() {
return SERVICE_INSTANCE;
}
private static InetAddress getLocalHostExactAddress() throws SocketException, UnknownHostException {<FILL_FUNCTION_BODY>}
}
|
InetAddress candidateAddress = null;
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
for (Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
if (!networkInterface.isPointToPoint()) {
return inetAddress;
} else {
candidateAddress = inetAddress;
}
}
}
}
return candidateAddress == null ? InetAddress.getLocalHost() : candidateAddress;
| 414
| 197
| 611
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/ConstructorUtil.java
|
ConstructorUtil
|
buildTpExecutorConstructorArgTypes
|
class ConstructorUtil {
private ConstructorUtil() { }
public static Object[] buildTpExecutorConstructorArgs(ThreadPoolExecutor dtpExecutor) {
return new Object[] {
dtpExecutor.getCorePoolSize(),
dtpExecutor.getMaximumPoolSize(),
dtpExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS),
TimeUnit.MILLISECONDS,
dtpExecutor.getQueue(),
dtpExecutor.getThreadFactory(),
dtpExecutor.getRejectedExecutionHandler()
};
}
public static Class<?>[] buildTpExecutorConstructorArgTypes() {<FILL_FUNCTION_BODY>}
public static Class<?>[] buildConstructorArgs() {
return new Class[0];
}
public static Class<?>[] buildConstructorArgTypes(Object obj) {
Class<?> clazz = obj.getClass();
Constructor<?>[] constructors = clazz.getConstructors();
if (constructors.length > 0) {
return constructors[0].getParameterTypes();
}
return new Class[0];
}
}
|
return new Class[] {
int.class,
int.class,
long.class,
TimeUnit.class,
BlockingQueue.class,
ThreadFactory.class,
RejectedExecutionHandler.class
};
| 287
| 62
| 349
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/DingSignUtil.java
|
DingSignUtil
|
dingSign
|
class DingSignUtil {
private DingSignUtil() { }
/**
* The default encoding
*/
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
/**
* Signature method
*/
private static final String ALGORITHM = "HmacSHA256";
public static String dingSign(String secret, long timestamp) {<FILL_FUNCTION_BODY>}
}
|
String stringToSign = timestamp + "\n" + secret;
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(secret.getBytes(DEFAULT_ENCODING), ALGORITHM));
byte[] signData = mac.doFinal(stringToSign.getBytes(DEFAULT_ENCODING));
return URLEncoder.encode(new String(Base64.encodeBase64(signData)), DEFAULT_ENCODING.name());
} catch (Exception e) {
log.error("DynamicTp, cal ding sign error", e);
return "";
}
| 118
| 161
| 279
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/ExtensionServiceLoader.java
|
ExtensionServiceLoader
|
load
|
class ExtensionServiceLoader {
private static final Map<Class<?>, List<?>> EXTENSION_MAP = new ConcurrentHashMap<>();
private ExtensionServiceLoader() { }
/**
* load service
* @param clazz SPI interface
* @return services
* @param <T> interface class
*/
@SuppressWarnings("unchecked")
public static <T> List<T> get(Class<T> clazz) {
List<T> services = (List<T>) EXTENSION_MAP.get(clazz);
if (CollectionUtils.isEmpty(services)) {
services = load(clazz);
if (CollectionUtils.isNotEmpty(services)) {
EXTENSION_MAP.put(clazz, services);
}
}
return services;
}
/**
* load the first service
* @param clazz SPI interface
* @return service
* @param <T> interface class
*/
public static <T> T getFirst(Class<T> clazz) {
List<T> services = get(clazz);
return CollectionUtils.isEmpty(services) ? null : services.get(0);
}
private static <T> List<T> load(Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
List<T> services = new ArrayList<>();
for (T service : serviceLoader) {
services.add(service);
}
return services;
| 337
| 60
| 397
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/JsonUtil.java
|
JsonUtil
|
createJsonParser
|
class JsonUtil {
private static final JsonParser JSON_PARSER = createJsonParser();
private static JsonParser createJsonParser() {<FILL_FUNCTION_BODY>}
/**
* 方法注释: <br>
* 〈可用于将任何 Java 值序列化为字符串的方法。〉
*
* @param obj 任意类型入参
* @return java.lang.String
* @author topsuder 🌼🐇
*/
public static String toJson(Object obj) {
return JSON_PARSER.toJson(obj);
}
/**
* 方法注释: <br>
* 〈此方法将指定的 Json 反序列化为指定类的对象。〉
*
* @param <T> the target type
* @param json 要反序列化的json字符串
* @param typeOfT 要反序列化的对象类型
* @return T
* @author topsuder 🌼🐇
*/
public static <T> T fromJson(String json, Type typeOfT) {
return JSON_PARSER.fromJson(json, typeOfT);
}
}
|
ServiceLoader<JsonParser> serviceLoader = ServiceLoader.load(JsonParser.class);
Iterator<JsonParser> iterator = serviceLoader.iterator();
while (iterator.hasNext()) {
try {
JsonParser jsonParser = iterator.next();
if (jsonParser.supports()) {
return jsonParser;
}
} catch (Throwable ignored) {
}
}
throw new IllegalStateException("No JSON parser found");
| 308
| 115
| 423
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/MethodUtil.java
|
MethodUtil
|
invokeAndReturnLong
|
class MethodUtil {
private MethodUtil() { }
/**
* Invoke method and return double value.
*
* @param method target method
* @param targetObj the object the underlying method is invoked from
* @return result
*/
public static double invokeAndReturnDouble(Method method, Object targetObj) {
try {
return method != null ? (double) method.invoke(targetObj) : -1;
} catch (Exception e) {
return -1;
}
}
/**
* Invoke method and return long value.
*
* @param method target method
* @param targetObj the object the underlying method is invoked from
* @return result
*/
public static long invokeAndReturnLong(Method method, Object targetObj) {<FILL_FUNCTION_BODY>}
}
|
try {
return method != null ? (long) method.invoke(targetObj) : -1;
} catch (Exception e) {
return -1;
}
| 213
| 47
| 260
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/ReflectionUtil.java
|
ReflectionUtil
|
setFieldValue
|
class ReflectionUtil {
private ReflectionUtil() { }
public static Object getFieldValue(String fieldName, Object targetObj) {
val field = getField(targetObj.getClass(), fieldName);
if (Objects.isNull(field)) {
return null;
}
val fieldObj = ReflectionUtils.getField(field, targetObj);
if (Objects.isNull(fieldObj)) {
return null;
}
return fieldObj;
}
public static Object getFieldValue(Class<?> targetClass, String fieldName, Object targetObj) {
val field = getField(targetClass, fieldName);
if (Objects.isNull(field)) {
return null;
}
val fieldObj = ReflectionUtils.getField(field, targetObj);
if (Objects.isNull(fieldObj)) {
return null;
}
return fieldObj;
}
public static void setFieldValue(String fieldName, Object targetObj, Object targetVal)
throws IllegalAccessException {<FILL_FUNCTION_BODY>}
public static void setFieldValue(Class<?> targetClass, String fieldName, Object targetObj, Object targetVal)
throws IllegalAccessException {
val field = getField(targetClass, fieldName);
if (Objects.isNull(field)) {
return;
}
field.set(targetObj, targetVal);
}
public static Field getField(Class<?> targetClass, String fieldName) {
Field field = ReflectionUtils.findField(targetClass, fieldName);
if (Objects.isNull(field)) {
return null;
}
ReflectionUtils.makeAccessible(field);
return field;
}
}
|
val field = getField(targetObj.getClass(), fieldName);
if (Objects.isNull(field)) {
return;
}
field.set(targetObj, targetVal);
| 434
| 51
| 485
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/StreamUtil.java
|
StreamUtil
|
toMap
|
class StreamUtil {
private StreamUtil() { }
/**
* Fetches id to list.
*
* @param data data collection
* @param mapping calculate the id in data list
* @param <I> id type
* @param <T> data type
* @return a list of id
*/
public static <I, T> List<I> fetchProperty(Collection<T> data,
Function<T, I> mapping) {
Assert.notNull(mapping, "mapping function must not be null");
if (CollectionUtils.isEmpty(data)) {
return Collections.emptyList();
}
return data.stream().map(mapping).collect(Collectors.toList());
}
/**
* Converts to map (key from the list data)
*
* @param coll data list
* @param key key mapping function
* @param <O> id type
* @param <P> data type
* @return a map which key from list data and value is data
*/
public static <P, O> Map<O, P> toMap(Collection<P> coll, Function<P, O> key) {
Assert.notNull(key, "key function must not be null");
if (CollectionUtils.isEmpty(coll)) {
return Collections.emptyMap();
}
return coll.stream().collect(Collectors.toMap(key, Function.identity(), (v1, v2) -> v2));
}
/**
* Converts to map (key from the list data)
*
* @param list data list
* @param key key mapping function
* @param value value mapping function
* @param <O> id type
* @param <D> data type
* @param <P> value type
* @return a map which key from list data and value is data
*/
public static <O, D, P> Map<O, P> toMap(Collection<D> list,
Function<D, O> key,
Function<D, P> value) {<FILL_FUNCTION_BODY>}
/**
* Converts a list to a list map where list contains id in ids.
*
* @param ids id collection
* @param list data list
* @param key calculate the id in data list
* @param <I> id type
* @param <D> data type
* @return a map which key is in ids and value containing in list
*/
public static <I, D> Map<I, List<D>> toListMap(Collection<I> ids,
Collection<D> list,
Function<D, I> key) {
Assert.notNull(key, "mapping function must not be null");
if (CollectionUtils.isEmpty(ids) || CollectionUtils.isEmpty(list)) {
return Collections.emptyMap();
}
Map<I, List<D>> resultMap = list.stream().collect(Collectors.groupingBy(key));
ids.forEach(id -> resultMap.putIfAbsent(id, Collections.emptyList()));
return resultMap;
}
}
|
Assert.notNull(key, "Key function must not be null");
Assert.notNull(value, "Value function must not be null");
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyMap();
}
return list.stream().collect(Collectors.toMap(key, value, (v1, v2) -> v2));
| 797
| 92
| 889
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/StringUtil.java
|
StringUtil
|
getContainsStrIgnoreCase
|
class StringUtil {
private StringUtil() { }
public static boolean isEmpty(CharSequence str) {
return null == str || str.length() == 0;
}
public static boolean isNotEmpty(CharSequence str) {
return !isEmpty(str);
}
public static boolean containsIgnoreCase(CharSequence str, Collection<? extends CharSequence> testStrList) {
return null != getContainsStrIgnoreCase(str, testStrList);
}
public static String getContainsStrIgnoreCase(CharSequence str, Collection<? extends CharSequence> testStrList) {<FILL_FUNCTION_BODY>}
public static boolean containsIgnoreCase(CharSequence str, CharSequence testStr) {
if (null == str) {
return null == testStr;
}
return str.toString().toLowerCase().contains(testStr.toString().toLowerCase());
}
}
|
if (isEmpty(str) || CollectionUtils.isEmpty(testStrList)) {
return null;
}
CharSequence[] array = testStrList.toArray(new CharSequence[0]);
int size = testStrList.size();
for (int i = 0; i < size; ++i) {
CharSequence testStr = array[i];
if (containsIgnoreCase(str, testStr)) {
return testStr.toString();
}
}
return null;
| 225
| 122
| 347
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/VersionUtil.java
|
VersionUtil
|
version
|
class VersionUtil {
private static String version;
static {
try {
version = version();
} catch (Exception e) {
log.warn("no version number found");
}
}
private VersionUtil() { }
public static String version() {<FILL_FUNCTION_BODY>}
public static String getVersion() {
return version;
}
}
|
// find version info from MANIFEST.MF first
Package pkg = VersionUtil.class.getPackage();
String version;
if (pkg != null) {
version = pkg.getImplementationVersion();
if (StringUtils.isNotEmpty(version)) {
return version;
}
version = pkg.getSpecificationVersion();
if (StringUtils.isNotEmpty(version)) {
return version;
}
}
return "unknown";
| 105
| 122
| 227
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/aware/AwareManager.java
|
AwareManager
|
register
|
class AwareManager {
private static final List<ExecutorAware> EXECUTOR_AWARE_LIST = new ArrayList<>();
private AwareManager() { }
static {
EXECUTOR_AWARE_LIST.add(new PerformanceMonitorAware());
EXECUTOR_AWARE_LIST.add(new TaskTimeoutAware());
EXECUTOR_AWARE_LIST.add(new TaskRejectAware());
List<ExecutorAware> serviceLoader = ExtensionServiceLoader.get(ExecutorAware.class);
EXECUTOR_AWARE_LIST.addAll(serviceLoader);
EXECUTOR_AWARE_LIST.sort(Comparator.comparingInt(ExecutorAware::getOrder));
}
public static void add(ExecutorAware aware) {
for (ExecutorAware executorAware : EXECUTOR_AWARE_LIST) {
if (executorAware.getName().equalsIgnoreCase(aware.getName())) {
return;
}
}
EXECUTOR_AWARE_LIST.add(aware);
EXECUTOR_AWARE_LIST.sort(Comparator.comparingInt(ExecutorAware::getOrder));
}
public static void register(ExecutorWrapper executorWrapper) {<FILL_FUNCTION_BODY>}
public static void refresh(ExecutorWrapper executorWrapper, TpExecutorProps props) {
for (ExecutorAware executorAware : EXECUTOR_AWARE_LIST) {
val awareNames = props.getAwareNames();
if (CollectionUtils.isEmpty(awareNames) || awareNames.contains(executorAware.getName())) {
executorAware.refresh(executorWrapper, props);
} else {
executorAware.remove(executorWrapper);
}
}
}
public static void execute(Executor executor, Runnable r) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.execute(executor, r);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance execute error.", aware.getName(), e);
}
}
}
public static void beforeExecute(Executor executor, Thread t, Runnable r) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.beforeExecute(executor, t, r);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance beforeExecute error.", aware.getName(), e);
}
}
}
public static void afterExecute(Executor executor, Runnable r, Throwable t) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.afterExecute(executor, r, t);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance afterExecute error.", aware.getName(), e);
}
}
}
public static void shutdown(Executor executor) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.shutdown(executor);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance shutdown error.", aware.getName(), e);
}
}
}
public static void shutdownNow(Executor executor, List<Runnable> tasks) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.shutdownNow(executor, tasks);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance shutdownNow error.", aware.getName(), e);
}
}
}
public static void terminated(Executor executor) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.terminated(executor);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance terminated error.", aware.getName(), e);
}
}
}
public static void beforeReject(Runnable r, Executor executor) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.beforeReject(r, executor);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance beforeReject error.", aware.getName(), e);
}
}
}
public static void afterReject(Runnable r, Executor executor) {
for (ExecutorAware aware : EXECUTOR_AWARE_LIST) {
try {
aware.afterReject(r, executor);
} catch (Exception e) {
log.error("DynamicTp aware [{}], enhance afterReject error.", aware.getName(), e);
}
}
}
}
|
for (ExecutorAware executorAware : EXECUTOR_AWARE_LIST) {
val awareNames = executorWrapper.getAwareNames();
// if awareNames is empty, register all
if (CollectionUtils.isEmpty(awareNames) || awareNames.contains(executorAware.getName())) {
executorAware.register(executorWrapper);
}
}
| 1,251
| 98
| 1,349
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/aware/TaskRejectAware.java
|
TaskRejectAware
|
beforeReject
|
class TaskRejectAware extends TaskStatAware {
@Override
public int getOrder() {
return AwareTypeEnum.TASK_REJECT_AWARE.getOrder();
}
@Override
public String getName() {
return AwareTypeEnum.TASK_REJECT_AWARE.getName();
}
@Override
public void beforeReject(Runnable runnable, Executor executor) {<FILL_FUNCTION_BODY>}
}
|
ThreadPoolStatProvider statProvider = statProviders.get(executor);
if (Objects.isNull(statProvider)) {
return;
}
statProvider.incRejectCount(1);
AlarmManager.tryAlarmAsync(statProvider.getExecutorWrapper(), REJECT, runnable);
ExecutorAdapter<?> executorAdapter = statProvider.getExecutorWrapper().getExecutor();
String logMsg = CharSequenceUtil.format("DynamicTp execute, thread pool is exhausted, tpName: {}, traceId: {}, " +
"poolSize: {} (active: {}, core: {}, max: {}, largest: {}), " +
"task: {} (completed: {}), queueCapacity: {}, (currSize: {}, remaining: {}) ," +
"executorStatus: (isShutdown: {}, isTerminated: {}, isTerminating: {})",
statProvider.getExecutorWrapper().getThreadPoolName(), MDC.get(TRACE_ID), executorAdapter.getPoolSize(),
executorAdapter.getActiveCount(), executorAdapter.getCorePoolSize(), executorAdapter.getMaximumPoolSize(),
executorAdapter.getLargestPoolSize(), executorAdapter.getTaskCount(), executorAdapter.getCompletedTaskCount(),
statProvider.getExecutorWrapper().getExecutor().getQueueCapacity(), executorAdapter.getQueue().size(),
executorAdapter.getQueue().remainingCapacity(),
executorAdapter.isShutdown(), executorAdapter.isTerminated(), executorAdapter.isTerminating());
log.warn(logMsg);
| 126
| 380
| 506
|
<methods>public non-sealed void <init>() ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, org.dromara.dynamictp.common.entity.TpExecutorProps) ,public void register(org.dromara.dynamictp.core.support.ExecutorWrapper) ,public void remove(org.dromara.dynamictp.core.support.ExecutorWrapper) <variables>protected final Map<java.util.concurrent.Executor,org.dromara.dynamictp.core.support.ThreadPoolStatProvider> statProviders
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/aware/TaskStatAware.java
|
TaskStatAware
|
refresh
|
class TaskStatAware implements ExecutorAware {
protected final Map<Executor, ThreadPoolStatProvider> statProviders = new ConcurrentHashMap<>();
@Override
public void register(ExecutorWrapper wrapper) {
ThreadPoolStatProvider statProvider = wrapper.getThreadPoolStatProvider();
statProviders.put(wrapper.getExecutor(), statProvider);
statProviders.put(wrapper.getExecutor().getOriginal(), statProvider);
}
@Override
public void refresh(ExecutorWrapper wrapper, TpExecutorProps props) {<FILL_FUNCTION_BODY>}
@Override
public void remove(ExecutorWrapper wrapper) {
statProviders.remove(wrapper.getExecutor());
statProviders.remove(wrapper.getExecutor().getOriginal());
}
protected void refresh(TpExecutorProps props, ThreadPoolStatProvider statProvider) { }
}
|
if (Objects.isNull(statProviders.get(wrapper.getExecutor()))) {
register(wrapper);
}
ThreadPoolStatProvider statProvider = wrapper.getThreadPoolStatProvider();
refresh(props, statProvider);
| 214
| 60
| 274
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/aware/TaskTimeoutAware.java
|
TaskTimeoutAware
|
refresh
|
class TaskTimeoutAware extends TaskStatAware {
@Override
public int getOrder() {
return AwareTypeEnum.TASK_TIMEOUT_AWARE.getOrder();
}
@Override
public String getName() {
return AwareTypeEnum.TASK_TIMEOUT_AWARE.getName();
}
@Override
protected void refresh(TpExecutorProps props, ThreadPoolStatProvider statProvider) {<FILL_FUNCTION_BODY>}
@Override
public void execute(Executor executor, Runnable r) {
if (TRUE_STR.equals(System.getProperty(DTP_EXECUTE_ENHANCED, TRUE_STR))) {
Optional.ofNullable(statProviders.get(executor)).ifPresent(p -> p.startQueueTimeoutTask(r));
}
}
@Override
public void beforeExecute(Executor executor, Thread t, Runnable r) {
Optional.ofNullable(statProviders.get(executor)).ifPresent(p -> {
p.cancelQueueTimeoutTask(r);
p.startRunTimeoutTask(t, r);
});
}
@Override
public void afterExecute(Executor executor, Runnable r, Throwable t) {
Optional.ofNullable(statProviders.get(executor)).ifPresent(p -> p.cancelRunTimeoutTask(r));
}
@Override
public void beforeReject(Runnable r, Executor executor) {
Optional.ofNullable(statProviders.get(executor)).ifPresent(p -> p.cancelQueueTimeoutTask(r));
}
}
|
super.refresh(props, statProvider);
if (Objects.nonNull(props)) {
statProvider.setRunTimeout(props.getRunTimeout());
statProvider.setQueueTimeout(props.getQueueTimeout());
statProvider.setTryInterrupt(props.isTryInterrupt());
}
| 412
| 77
| 489
|
<methods>public non-sealed void <init>() ,public void refresh(org.dromara.dynamictp.core.support.ExecutorWrapper, org.dromara.dynamictp.common.entity.TpExecutorProps) ,public void register(org.dromara.dynamictp.core.support.ExecutorWrapper) ,public void remove(org.dromara.dynamictp.core.support.ExecutorWrapper) <variables>protected final Map<java.util.concurrent.Executor,org.dromara.dynamictp.core.support.ThreadPoolStatProvider> statProviders
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/converter/ExecutorConverter.java
|
ExecutorConverter
|
toMetrics
|
class ExecutorConverter {
private ExecutorConverter() {
}
public static TpMainFields toMainFields(ExecutorWrapper executorWrapper) {
TpMainFields mainFields = new TpMainFields();
mainFields.setThreadPoolName(executorWrapper.getThreadPoolName());
val executor = executorWrapper.getExecutor();
mainFields.setCorePoolSize(executor.getCorePoolSize());
mainFields.setMaxPoolSize(executor.getMaximumPoolSize());
mainFields.setKeepAliveTime(executor.getKeepAliveTime(TimeUnit.SECONDS));
mainFields.setQueueType(executor.getQueueType());
mainFields.setQueueCapacity(executor.getQueueCapacity());
mainFields.setAllowCoreThreadTimeOut(executor.allowsCoreThreadTimeOut());
mainFields.setRejectType(executor.getRejectHandlerType());
return mainFields;
}
public static ThreadPoolStats toMetrics(ExecutorWrapper wrapper) {<FILL_FUNCTION_BODY>}
private static ThreadPoolStats convertCommon(ExecutorAdapter<?> executor) {
ThreadPoolStats poolStats = new ThreadPoolStats();
poolStats.setCorePoolSize(executor.getCorePoolSize());
poolStats.setMaximumPoolSize(executor.getMaximumPoolSize());
poolStats.setPoolSize(executor.getPoolSize());
poolStats.setActiveCount(executor.getActiveCount());
poolStats.setLargestPoolSize(executor.getLargestPoolSize());
poolStats.setQueueType(executor.getQueueType());
poolStats.setQueueCapacity(executor.getQueueCapacity());
poolStats.setQueueSize(executor.getQueueSize());
poolStats.setQueueRemainingCapacity(executor.getQueueRemainingCapacity());
poolStats.setTaskCount(executor.getTaskCount());
poolStats.setCompletedTaskCount(executor.getCompletedTaskCount());
poolStats.setWaitTaskCount(executor.getQueueSize());
poolStats.setRejectHandlerName(executor.getRejectHandlerType());
return poolStats;
}
}
|
ExecutorAdapter<?> executor = wrapper.getExecutor();
if (executor == null) {
return null;
}
ThreadPoolStatProvider provider = wrapper.getThreadPoolStatProvider();
PerformanceProvider performanceProvider = provider.getPerformanceProvider();
val performanceSnapshot = performanceProvider.getSnapshotAndReset();
ThreadPoolStats poolStats = convertCommon(executor);
poolStats.setPoolName(wrapper.getThreadPoolName());
poolStats.setPoolAliasName(wrapper.getThreadPoolAliasName());
poolStats.setRunTimeoutCount(provider.getRunTimeoutCount());
poolStats.setQueueTimeoutCount(provider.getQueueTimeoutCount());
poolStats.setRejectCount(provider.getRejectedTaskCount());
poolStats.setDynamic(executor instanceof DtpExecutor);
poolStats.setTps(performanceSnapshot.getTps());
poolStats.setAvg(performanceSnapshot.getAvg());
poolStats.setMaxRt(performanceSnapshot.getMaxRt());
poolStats.setMinRt(performanceSnapshot.getMinRt());
poolStats.setTp50(performanceSnapshot.getTp50());
poolStats.setTp75(performanceSnapshot.getTp75());
poolStats.setTp90(performanceSnapshot.getTp90());
poolStats.setTp95(performanceSnapshot.getTp95());
poolStats.setTp99(performanceSnapshot.getTp99());
poolStats.setTp999(performanceSnapshot.getTp999());
return poolStats;
| 542
| 395
| 937
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/executor/NamedThreadFactory.java
|
NamedThreadFactory
|
newThread
|
class NamedThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final String namePrefix;
/**
* is daemon thread.
*/
private final boolean daemon;
/**
* thread priority.
*/
private final Integer priority;
/**
* thread name index.
*/
private final AtomicInteger seq = new AtomicInteger(1);
public NamedThreadFactory(String namePrefix, boolean daemon, int priority) {
this.daemon = daemon;
this.priority = priority;
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix;
}
public NamedThreadFactory(String namePrefix) {
this(namePrefix, false, Thread.NORM_PRIORITY);
}
public NamedThreadFactory(String namePrefix, boolean daemon) {
this(namePrefix, daemon, Thread.NORM_PRIORITY);
}
@Override
public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>}
public String getNamePrefix() {
return namePrefix;
}
}
|
String name = namePrefix + "-" + seq.getAndIncrement();
Thread t = new Thread(group, r, name);
t.setDaemon(daemon);
t.setPriority(priority);
return t;
| 321
| 62
| 383
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/executor/OrderedDtpExecutor.java
|
OrderedDtpExecutor
|
submit
|
class OrderedDtpExecutor extends DtpExecutor {
private final ExecutorSelector selector = new HashedExecutorSelector();
private final List<Executor> childExecutors = Lists.newArrayList();
public OrderedDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), new AbortPolicy());
}
public OrderedDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, new AbortPolicy());
}
public OrderedDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
public OrderedDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
for (int i = 0; i < corePoolSize; i++) {
ChildExecutor childExecutor = new ChildExecutor(workQueue.size() + workQueue.remainingCapacity());
childExecutors.add(childExecutor);
}
}
@Override
public void execute(Runnable command) {
if (command == null) {
throw new NullPointerException();
}
if (command instanceof Ordered) {
doOrderedExecute(command, ((Ordered) command).hashKey());
} else {
doUnorderedExecute(command);
}
}
public void execute(Runnable command, Object hashKey) {
if (Objects.nonNull(hashKey)) {
doOrderedExecute(command, hashKey);
} else {
doUnorderedExecute(command);
}
}
@Override
public <T> Future<T> submit(Callable<T> task) {
if (task == null) {
throw new NullPointerException();
}
Object hashKey = task instanceof Ordered ? ((Ordered) task).hashKey() : null;
RunnableFuture<T> futureTask = newTaskFor(task);
execute(futureTask, hashKey);
return futureTask;
}
public <T> Future<T> submit(Callable<T> task, Object hashKey) {<FILL_FUNCTION_BODY>}
private void doOrderedExecute(Runnable command, Object hashKey) {
Executor executor = selector.select(childExecutors, hashKey);
executor.execute(command);
}
private void doUnorderedExecute(Runnable command) {
super.execute(command);
}
void onBeforeExecute(Thread t, Runnable r) {
beforeExecute(t, r);
}
void onAfterExecute(Runnable r, Throwable t) {
afterExecute(r, t);
}
@Override
public long getCompletedTaskCount() {
long count = 0;
for (Executor executor : childExecutors) {
count += ((ChildExecutor) executor).getCompletedTaskCount();
}
return super.getCompletedTaskCount() + count;
}
@Override
public long getTaskCount() {
long count = 0;
for (Executor executor : childExecutors) {
count += ((ChildExecutor) executor).getTaskCount();
}
return super.getTaskCount() + count;
}
@Override
public void onRefreshQueueCapacity(int capacity) {
for (Executor executor : childExecutors) {
ChildExecutor childExecutor = (ChildExecutor) executor;
if (childExecutor.getTaskQueue() instanceof VariableLinkedBlockingQueue) {
((VariableLinkedBlockingQueue<Runnable>) childExecutor.getTaskQueue()).setCapacity(capacity);
}
}
}
private final class ChildExecutor implements Executor, Runnable {
private final BlockingQueue<Runnable> taskQueue;
private final LongAdder completedTaskCount = new LongAdder();
private final LongAdder rejectedTaskCount = new LongAdder();
private boolean running;
ChildExecutor(int queueSize) {
if (queueSize <= 0) {
taskQueue = new SynchronousQueue<>();
return;
}
taskQueue = new VariableLinkedBlockingQueue<>(queueSize);
}
@Override
public void execute(Runnable command) {
boolean start = false;
command = getEnhancedTask(command, getTaskWrappers());
synchronized (this) {
try {
if (!taskQueue.add(command)) {
rejectedTaskIncrement(command);
throw new RejectedExecutionException("Task " + command + " rejected from " + this);
}
} catch (IllegalStateException ex) {
rejectedTaskIncrement(command);
throw ex;
}
if (!running) {
running = true;
start = true;
}
}
if (start) {
doUnorderedExecute(this);
}
}
@Override
public void run() {
Thread thread = Thread.currentThread();
Runnable task;
while ((task = getTask()) != null) {
onBeforeExecute(thread, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x;
throw x;
} finally {
onAfterExecute(task, thrown);
completedTaskCount.increment();
}
}
}
private void rejectedTaskIncrement(Runnable runnable) {
AwareManager.beforeReject(runnable, OrderedDtpExecutor.this);
rejectedTaskCount.increment();
}
private synchronized Runnable getTask() {
Runnable task = taskQueue.poll();
if (task == null) {
running = false;
}
return task;
}
public BlockingQueue<Runnable> getTaskQueue() {
return taskQueue;
}
public long getTaskCount() {
return completedTaskCount.sum() + taskQueue.size();
}
public long getCompletedTaskCount() {
return completedTaskCount.sum();
}
@Override
public String toString() {
return super.toString() +
"[queue size = " + taskQueue.size() +
", completed tasks = " + completedTaskCount +
", rejected tasks = " + rejectedTaskCount +
", running = " + running +
"]";
}
}
}
|
if (task == null) {
throw new NullPointerException();
}
RunnableFuture<T> futureTask = newTaskFor(task);
execute(futureTask, hashKey);
return futureTask;
| 1,849
| 57
| 1,906
|
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void execute(java.lang.Runnable, long) ,public void execute(java.lang.Runnable) ,public int getAwaitTerminationSeconds() ,public Set<java.lang.String> getAwareNames() ,public List<org.dromara.dynamictp.common.entity.NotifyItem> getNotifyItems() ,public java.util.concurrent.ThreadPoolExecutor getOriginal() ,public List<java.lang.String> getPlatformIds() ,public Set<java.lang.String> getPluginNames() ,public long getQueueTimeout() ,public java.lang.String getRejectHandlerType() ,public long getRunTimeout() ,public List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> getTaskWrappers() ,public java.lang.String getThreadPoolAliasName() ,public java.lang.String getThreadPoolName() ,public void initialize() ,public boolean isNotifyEnabled() ,public boolean isPreStartAllCoreThreads() ,public boolean isRejectEnhanced() ,public boolean isTryInterrupt() ,public boolean isWaitForTasksToCompleteOnShutdown() ,public void setAllowCoreThreadTimeOut(boolean) ,public void setAwaitTerminationSeconds(int) ,public void setAwareNames(Set<java.lang.String>) ,public void setNotifyEnabled(boolean) ,public void setNotifyItems(List<org.dromara.dynamictp.common.entity.NotifyItem>) ,public void setPlatformIds(List<java.lang.String>) ,public void setPluginNames(Set<java.lang.String>) ,public void setPreStartAllCoreThreads(boolean) ,public void setQueueTimeout(long) ,public void setRejectEnhanced(boolean) ,public void setRejectHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setRejectHandlerType(java.lang.String) ,public void setRunTimeout(long) ,public void setTaskWrappers(List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper>) ,public void setThreadPoolAliasName(java.lang.String) ,public void setThreadPoolName(java.lang.String) ,public void setTryInterrupt(boolean) ,public void setWaitForTasksToCompleteOnShutdown(boolean) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() <variables>protected int awaitTerminationSeconds,private Set<java.lang.String> awareNames,private boolean notifyEnabled,private List<org.dromara.dynamictp.common.entity.NotifyItem> notifyItems,private List<java.lang.String> platformIds,private Set<java.lang.String> pluginNames,private boolean preStartAllCoreThreads,private long queueTimeout,private boolean rejectEnhanced,private java.lang.String rejectHandlerType,private long runTimeout,private List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> taskWrappers,private java.lang.String threadPoolAliasName,protected java.lang.String threadPoolName,private boolean tryInterrupt,protected boolean waitForTasksToCompleteOnShutdown
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/executor/eager/EagerDtpExecutor.java
|
EagerDtpExecutor
|
execute
|
class EagerDtpExecutor extends DtpExecutor {
/**
* The number of tasks submitted but not yet finished.
*/
private final AtomicInteger submittedTaskCount = new AtomicInteger(0);
public EagerDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), new AbortPolicy());
}
public EagerDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, new AbortPolicy());
}
public EagerDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
public EagerDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
public int getSubmittedTaskCount() {
return submittedTaskCount.get();
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
submittedTaskCount.decrementAndGet();
super.afterExecute(r, t);
}
@Override
public void execute(Runnable command) {<FILL_FUNCTION_BODY>}
}
|
if (command == null) {
throw new NullPointerException();
}
submittedTaskCount.incrementAndGet();
try {
super.execute(command);
} catch (RejectedExecutionException rx) {
if (getQueue() instanceof TaskQueue) {
// If the Executor is close to maximum pool size, concurrent
// calls to execute() may result (due to use of TaskQueue) in
// some tasks being rejected rather than queued.
// If this happens, add them to the queue.
final TaskQueue queue = (TaskQueue) getQueue();
try {
if (!queue.force(command, 0, TimeUnit.MILLISECONDS)) {
submittedTaskCount.decrementAndGet();
throw new RejectedExecutionException("Queue capacity is full.", rx);
}
} catch (InterruptedException x) {
submittedTaskCount.decrementAndGet();
throw new RejectedExecutionException(x);
}
} else {
submittedTaskCount.decrementAndGet();
throw rx;
}
}
| 528
| 269
| 797
|
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void execute(java.lang.Runnable, long) ,public void execute(java.lang.Runnable) ,public int getAwaitTerminationSeconds() ,public Set<java.lang.String> getAwareNames() ,public List<org.dromara.dynamictp.common.entity.NotifyItem> getNotifyItems() ,public java.util.concurrent.ThreadPoolExecutor getOriginal() ,public List<java.lang.String> getPlatformIds() ,public Set<java.lang.String> getPluginNames() ,public long getQueueTimeout() ,public java.lang.String getRejectHandlerType() ,public long getRunTimeout() ,public List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> getTaskWrappers() ,public java.lang.String getThreadPoolAliasName() ,public java.lang.String getThreadPoolName() ,public void initialize() ,public boolean isNotifyEnabled() ,public boolean isPreStartAllCoreThreads() ,public boolean isRejectEnhanced() ,public boolean isTryInterrupt() ,public boolean isWaitForTasksToCompleteOnShutdown() ,public void setAllowCoreThreadTimeOut(boolean) ,public void setAwaitTerminationSeconds(int) ,public void setAwareNames(Set<java.lang.String>) ,public void setNotifyEnabled(boolean) ,public void setNotifyItems(List<org.dromara.dynamictp.common.entity.NotifyItem>) ,public void setPlatformIds(List<java.lang.String>) ,public void setPluginNames(Set<java.lang.String>) ,public void setPreStartAllCoreThreads(boolean) ,public void setQueueTimeout(long) ,public void setRejectEnhanced(boolean) ,public void setRejectHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setRejectHandlerType(java.lang.String) ,public void setRunTimeout(long) ,public void setTaskWrappers(List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper>) ,public void setThreadPoolAliasName(java.lang.String) ,public void setThreadPoolName(java.lang.String) ,public void setTryInterrupt(boolean) ,public void setWaitForTasksToCompleteOnShutdown(boolean) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() <variables>protected int awaitTerminationSeconds,private Set<java.lang.String> awareNames,private boolean notifyEnabled,private List<org.dromara.dynamictp.common.entity.NotifyItem> notifyItems,private List<java.lang.String> platformIds,private Set<java.lang.String> pluginNames,private boolean preStartAllCoreThreads,private long queueTimeout,private boolean rejectEnhanced,private java.lang.String rejectHandlerType,private long runTimeout,private List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> taskWrappers,private java.lang.String threadPoolAliasName,protected java.lang.String threadPoolName,private boolean tryInterrupt,protected boolean waitForTasksToCompleteOnShutdown
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/executor/eager/TaskQueue.java
|
TaskQueue
|
offer
|
class TaskQueue extends VariableLinkedBlockingQueue<Runnable> {
private static final long serialVersionUID = -1L;
private transient EagerDtpExecutor executor;
public TaskQueue(int queueCapacity) {
super(queueCapacity);
}
public void setExecutor(EagerDtpExecutor exec) {
executor = exec;
}
@Override
public boolean offer(@NonNull Runnable runnable) {<FILL_FUNCTION_BODY>}
/**
* Force offer task
*
* @param o task
* @param timeout timeout
* @param unit unit
* @return offer success or not
* @throws RejectedExecutionException if executor is terminated.
* @throws InterruptedException if interrupted while waiting.
*/
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (executor.isShutdown()) {
throw new RejectedExecutionException("Executor is shutdown.");
}
return super.offer(o, timeout, unit);
}
}
|
if (executor == null) {
throw new RejectedExecutionException("The task queue does not have executor.");
}
int currentPoolThreadSize = executor.getPoolSize();
if (currentPoolThreadSize == executor.getMaximumPoolSize()) {
return super.offer(runnable);
}
// have free worker. put task into queue to let the worker deal with task.
if (executor.getSubmittedTaskCount() < 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);
| 274
| 198
| 472
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends java.lang.Runnable>) ,public void clear() ,public boolean contains(java.lang.Object) ,public int drainTo(Collection<? super java.lang.Runnable>) ,public int drainTo(Collection<? super java.lang.Runnable>, int) ,public Iterator<java.lang.Runnable> iterator() ,public boolean offer(java.lang.Runnable, long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public boolean offer(java.lang.Runnable) ,public java.lang.Runnable peek() ,public java.lang.Runnable poll(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public java.lang.Runnable poll() ,public void put(java.lang.Runnable) throws java.lang.InterruptedException,public int remainingCapacity() ,public boolean remove(java.lang.Object) ,public void setCapacity(int) ,public int size() ,public Spliterator<java.lang.Runnable> spliterator() ,public java.lang.Runnable take() throws java.lang.InterruptedException,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>private int capacity,private final java.util.concurrent.atomic.AtomicInteger count,transient Node<java.lang.Runnable> head,private transient Node<java.lang.Runnable> last,private final java.util.concurrent.locks.Condition notEmpty,private final java.util.concurrent.locks.Condition notFull,private final java.util.concurrent.locks.ReentrantLock putLock,private static final long serialVersionUID,private final java.util.concurrent.locks.ReentrantLock takeLock
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/executor/priority/PriorityDtpExecutor.java
|
PriorityDtpExecutor
|
getRunnableComparator
|
class PriorityDtpExecutor extends DtpExecutor {
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
int capacity) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<>(capacity), Executors.defaultThreadFactory(), new AbortPolicy());
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
int capacity,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<>(capacity), threadFactory, new AbortPolicy());
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
int capacity,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<>(capacity), Executors.defaultThreadFactory(), handler);
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
int capacity,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<>(capacity), threadFactory, handler);
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
PriorityBlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), new AbortPolicy());
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
PriorityBlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new AbortPolicy());
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
PriorityBlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler);
}
public PriorityDtpExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
PriorityBlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new PriorityFutureTask<>(runnable, value);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new PriorityFutureTask<>(callable);
}
public void execute(Runnable command, int priority) {
super.execute(PriorityRunnable.of(command, priority));
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(PriorityRunnable.of(task, Priority.LOWEST_PRECEDENCE));
}
public Future<?> submit(Runnable task, int priority) {
return super.submit(PriorityRunnable.of(task, priority));
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return super.submit(PriorityRunnable.of(task, Priority.LOWEST_PRECEDENCE), result);
}
public <T> Future<T> submit(Runnable task, T result, int priority) {
return super.submit(PriorityRunnable.of(task, priority), result);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(PriorityCallable.of(task, Priority.LOWEST_PRECEDENCE));
}
public <T> Future<T> submit(Callable<T> task, int priority) {
return super.submit(PriorityCallable.of(task, priority));
}
/**
* Priority Comparator
*
* @return Comparator
*/
public static Comparator<Runnable> getRunnableComparator() {<FILL_FUNCTION_BODY>}
}
|
return (o1, o2) -> {
if (!(o1 instanceof DtpRunnable) || !(o2 instanceof DtpRunnable)) {
return 0;
}
Runnable po1 = ((DtpRunnable) o1).getOriginRunnable();
Runnable po2 = ((DtpRunnable) o2).getOriginRunnable();
if (po1 instanceof Priority && po2 instanceof Priority) {
return Integer.compare(((Priority) po1).getPriority(), ((Priority) po2).getPriority());
}
return 0;
};
| 1,243
| 154
| 1,397
|
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void execute(java.lang.Runnable, long) ,public void execute(java.lang.Runnable) ,public int getAwaitTerminationSeconds() ,public Set<java.lang.String> getAwareNames() ,public List<org.dromara.dynamictp.common.entity.NotifyItem> getNotifyItems() ,public java.util.concurrent.ThreadPoolExecutor getOriginal() ,public List<java.lang.String> getPlatformIds() ,public Set<java.lang.String> getPluginNames() ,public long getQueueTimeout() ,public java.lang.String getRejectHandlerType() ,public long getRunTimeout() ,public List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> getTaskWrappers() ,public java.lang.String getThreadPoolAliasName() ,public java.lang.String getThreadPoolName() ,public void initialize() ,public boolean isNotifyEnabled() ,public boolean isPreStartAllCoreThreads() ,public boolean isRejectEnhanced() ,public boolean isTryInterrupt() ,public boolean isWaitForTasksToCompleteOnShutdown() ,public void setAllowCoreThreadTimeOut(boolean) ,public void setAwaitTerminationSeconds(int) ,public void setAwareNames(Set<java.lang.String>) ,public void setNotifyEnabled(boolean) ,public void setNotifyItems(List<org.dromara.dynamictp.common.entity.NotifyItem>) ,public void setPlatformIds(List<java.lang.String>) ,public void setPluginNames(Set<java.lang.String>) ,public void setPreStartAllCoreThreads(boolean) ,public void setQueueTimeout(long) ,public void setRejectEnhanced(boolean) ,public void setRejectHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setRejectHandlerType(java.lang.String) ,public void setRunTimeout(long) ,public void setTaskWrappers(List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper>) ,public void setThreadPoolAliasName(java.lang.String) ,public void setThreadPoolName(java.lang.String) ,public void setTryInterrupt(boolean) ,public void setWaitForTasksToCompleteOnShutdown(boolean) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() <variables>protected int awaitTerminationSeconds,private Set<java.lang.String> awareNames,private boolean notifyEnabled,private List<org.dromara.dynamictp.common.entity.NotifyItem> notifyItems,private List<java.lang.String> platformIds,private Set<java.lang.String> pluginNames,private boolean preStartAllCoreThreads,private long queueTimeout,private boolean rejectEnhanced,private java.lang.String rejectHandlerType,private long runTimeout,private List<org.dromara.dynamictp.core.support.task.wrapper.TaskWrapper> taskWrappers,private java.lang.String threadPoolAliasName,protected java.lang.String threadPoolName,private boolean tryInterrupt,protected boolean waitForTasksToCompleteOnShutdown
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/handler/CollectorHandler.java
|
CollectorHandler
|
collect
|
class CollectorHandler {
private static final Map<String, MetricsCollector> COLLECTORS = Maps.newHashMap();
private CollectorHandler() {
List<MetricsCollector> loadedCollectors = ExtensionServiceLoader.get(MetricsCollector.class);
loadedCollectors.forEach(collector -> COLLECTORS.put(collector.type(), collector));
MetricsCollector microMeterCollector = new MicroMeterCollector();
LogCollector logCollector = new LogCollector();
InternalLogCollector internalLogCollector = new InternalLogCollector();
JMXCollector jmxCollector = new JMXCollector();
COLLECTORS.put(microMeterCollector.type(), microMeterCollector);
COLLECTORS.put(logCollector.type(), logCollector);
COLLECTORS.put(internalLogCollector.type(), internalLogCollector);
COLLECTORS.put(jmxCollector.type(), jmxCollector);
}
public void collect(ThreadPoolStats poolStats, List<String> types) {<FILL_FUNCTION_BODY>}
public static CollectorHandler getInstance() {
return CollectorHandlerHolder.INSTANCE;
}
private static class CollectorHandlerHolder {
private static final CollectorHandler INSTANCE = new CollectorHandler();
}
}
|
if (poolStats == null || CollectionUtils.isEmpty(types)) {
return;
}
for (String collectorType : types) {
MetricsCollector collector = COLLECTORS.get(collectorType.toLowerCase());
if (collector != null) {
collector.collect(poolStats);
}
}
| 334
| 86
| 420
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/handler/ConfigHandler.java
|
ConfigHandler
|
parseConfig
|
class ConfigHandler {
private static final List<ConfigParser> PARSERS = Lists.newArrayList();
private ConfigHandler() {
List<ConfigParser> loadedParses = ExtensionServiceLoader.get(ConfigParser.class);
if (CollectionUtils.isNotEmpty(loadedParses)) {
PARSERS.addAll(loadedParses);
}
PARSERS.add(new PropertiesConfigParser());
PARSERS.add(new YamlConfigParser());
PARSERS.add(new JsonConfigParser());
}
public Map<Object, Object> parseConfig(String content, ConfigFileTypeEnum type) throws IOException {<FILL_FUNCTION_BODY>}
public static ConfigHandler getInstance() {
return ConfigHandlerHolder.INSTANCE;
}
private static class ConfigHandlerHolder {
private static final ConfigHandler INSTANCE = new ConfigHandler();
}
}
|
for (ConfigParser parser : PARSERS) {
if (parser.supports(type)) {
return parser.doParse(content);
}
}
return Collections.emptyMap();
| 225
| 54
| 279
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/handler/NotifierHandler.java
|
NotifierHandler
|
sendNotice
|
class NotifierHandler {
private static final Map<String, DtpNotifier> NOTIFIERS = new HashMap<>();
private NotifierHandler() {
List<DtpNotifier> loadedNotifiers = ExtensionServiceLoader.get(DtpNotifier.class);
loadedNotifiers.forEach(notifier -> NOTIFIERS.put(notifier.platform(), notifier));
DtpNotifier dingNotifier = new DtpDingNotifier(new DingNotifier());
DtpNotifier wechatNotifier = new DtpWechatNotifier(new WechatNotifier());
DtpNotifier larkNotifier = new DtpLarkNotifier(new LarkNotifier());
NOTIFIERS.put(dingNotifier.platform(), dingNotifier);
NOTIFIERS.put(wechatNotifier.platform(), wechatNotifier);
NOTIFIERS.put(larkNotifier.platform(), larkNotifier);
}
public void sendNotice(TpMainFields oldFields, List<String> diffs) {<FILL_FUNCTION_BODY>}
public void sendAlarm(NotifyItemEnum notifyItemEnum) {
NotifyItem notifyItem = DtpNotifyCtxHolder.get().getNotifyItem();
for (String platformId : notifyItem.getPlatformIds()) {
NotifyHelper.getPlatform(platformId).ifPresent(p -> {
DtpNotifier notifier = NOTIFIERS.get(p.getPlatform().toLowerCase());
if (notifier != null) {
notifier.sendAlarmMsg(p, notifyItemEnum);
}
});
}
}
public static NotifierHandler getInstance() {
return NotifierHandlerHolder.INSTANCE;
}
private static class NotifierHandlerHolder {
private static final NotifierHandler INSTANCE = new NotifierHandler();
}
}
|
NotifyItem notifyItem = DtpNotifyCtxHolder.get().getNotifyItem();
for (String platformId : notifyItem.getPlatformIds()) {
NotifyHelper.getPlatform(platformId).ifPresent(p -> {
DtpNotifier notifier = NOTIFIERS.get(p.getPlatform().toLowerCase());
if (notifier != null) {
notifier.sendChangeMsg(p, oldFields, diffs);
}
});
}
| 462
| 122
| 584
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/metric/LimitedUniformReservoir.java
|
LimitedUniformReservoir
|
getSnapshot
|
class LimitedUniformReservoir implements Reservoir {
private static final int DEFAULT_SIZE = 4096;
private static final int BITS_PER_LONG = 63;
private final AtomicLong count = new AtomicLong();
private volatile AtomicLongArray values = new AtomicLongArray(DEFAULT_SIZE);
@Override
public int size() {
final long c = count.get();
if (c > values.length()) {
return values.length();
}
return (int) c;
}
@Override
public void update(long value) {
final long c = count.incrementAndGet();
if (c <= values.length()) {
values.set((int) c - 1, value);
} else {
final long r = nextLong(c);
if (r < values.length()) {
values.set((int) r, value);
}
}
}
@Override
public Snapshot getSnapshot() {<FILL_FUNCTION_BODY>}
public void reset() {
count.set(0);
values = new AtomicLongArray(DEFAULT_SIZE);
}
private static long nextLong(long n) {
long bits;
long val;
do {
bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG));
val = bits % n;
} while (bits - val + (n - 1) < 0L);
return val;
}
}
|
final int s = size();
final List<Long> copy = new ArrayList<>(s);
for (int i = 0; i < s; i++) {
copy.add(values.get(i));
}
return new UniformSnapshot(copy);
| 392
| 68
| 460
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/metric/MMACounter.java
|
MMACounter
|
getAvg
|
class MMACounter implements Summary {
private final AtomicLong total = new AtomicLong();
private final AtomicLong count = new AtomicLong();
private final AtomicLong min = new AtomicLong(Long.MAX_VALUE);
private final AtomicLong max = new AtomicLong(Long.MIN_VALUE);
@Override
public void add(long value) {
total.addAndGet(value);
count.incrementAndGet();
setMin(value);
setMax(value);
}
@Override
public void reset() {
total.set(0);
count.set(0);
min.set(Long.MAX_VALUE);
max.set(Long.MIN_VALUE);
}
public long getTotal() {
return total.get();
}
public long getCount() {
return count.get();
}
public long getMin() {
long current = min.get();
return (current == Long.MAX_VALUE) ? 0 : current;
}
public long getMax() {
long current = max.get();
return (current == Long.MIN_VALUE) ? 0 : current;
}
public double getAvg() {<FILL_FUNCTION_BODY>}
private void setMax(long value) {
long current;
while (value > (current = max.get()) && !max.compareAndSet(current, value)) {
// no op
}
}
private void setMin(long value) {
long current;
while (value < (current = min.get()) && !min.compareAndSet(current, value)) {
// no op
}
}
}
|
long currentCount = count.get();
long currentTotal = total.get();
if (currentCount > 0) {
double avgLatency = currentTotal / (double) currentCount;
BigDecimal bg = new BigDecimal(avgLatency);
return bg.setScale(4, RoundingMode.HALF_UP).doubleValue();
}
return 0;
| 434
| 99
| 533
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/monitor/DtpMonitor.java
|
DtpMonitor
|
collectMetrics
|
class DtpMonitor extends OnceApplicationContextEventListener {
private static final ScheduledExecutorService MONITOR_EXECUTOR = ThreadPoolCreator.newScheduledThreadPool("dtp-monitor", 1);
private final DtpProperties dtpProperties;
private ScheduledFuture<?> monitorFuture;
private int monitorInterval;
public DtpMonitor(DtpProperties dtpProperties) {
this.dtpProperties = dtpProperties;
}
@Override
protected synchronized void onContextRefreshedEvent(ContextRefreshedEvent event) {
// if monitorInterval is same as before, do nothing.
if (monitorInterval == dtpProperties.getMonitorInterval()) {
return;
}
// cancel old monitor task.
if (monitorFuture != null) {
monitorFuture.cancel(true);
}
monitorInterval = dtpProperties.getMonitorInterval();
monitorFuture = MONITOR_EXECUTOR.scheduleWithFixedDelay(this::run,
0, dtpProperties.getMonitorInterval(), TimeUnit.SECONDS);
}
private void run() {
Set<String> executorNames = DtpRegistry.getAllExecutorNames();
checkAlarm(executorNames);
collectMetrics(executorNames);
}
private void checkAlarm(Set<String> executorNames) {
executorNames.forEach(name -> {
ExecutorWrapper wrapper = DtpRegistry.getExecutorWrapper(name);
AlarmManager.tryAlarmAsync(wrapper, SCHEDULE_NOTIFY_ITEMS);
});
publishAlarmCheckEvent();
}
private void collectMetrics(Set<String> executorNames) {<FILL_FUNCTION_BODY>}
private void doCollect(ThreadPoolStats threadPoolStats) {
try {
CollectorHandler.getInstance().collect(threadPoolStats, dtpProperties.getCollectorTypes());
} catch (Exception e) {
log.error("DynamicTp monitor, metrics collect error.", e);
}
}
private void publishCollectEvent() {
CollectEvent event = new CollectEvent(this, dtpProperties);
ApplicationContextHolder.publishEvent(event);
}
private void publishAlarmCheckEvent() {
AlarmCheckEvent event = new AlarmCheckEvent(this, dtpProperties);
ApplicationContextHolder.publishEvent(event);
}
public static void destroy() {
MONITOR_EXECUTOR.shutdownNow();
}
}
|
if (!dtpProperties.isEnabledCollect()) {
return;
}
executorNames.forEach(x -> {
ExecutorWrapper wrapper = DtpRegistry.getExecutorWrapper(x);
doCollect(ExecutorConverter.toMetrics(wrapper));
});
publishCollectEvent();
| 627
| 74
| 701
|
<methods>public void onApplicationEvent(ApplicationEvent) ,public final void setApplicationContext(ApplicationContext) <variables>private ApplicationContext applicationContext
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/monitor/PerformanceProvider.java
|
PerformanceProvider
|
getSnapshotAndReset
|
class PerformanceProvider {
/**
* last refresh timestamp
*/
private final AtomicLong lastRefreshMillis = new AtomicLong(System.currentTimeMillis());
private final MMAPCounter mmapCounter = new MMAPCounter();
public void completeTask(long rt) {
mmapCounter.add(rt);
}
public PerformanceSnapshot getSnapshotAndReset() {<FILL_FUNCTION_BODY>}
private void reset(long currentMillis) {
mmapCounter.reset();
lastRefreshMillis.compareAndSet(lastRefreshMillis.get(), currentMillis);
}
@Getter
public static class PerformanceSnapshot {
private final double tps;
private final long maxRt;
private final long minRt;
private final double avg;
private final double tp50;
private final double tp75;
private final double tp90;
private final double tp95;
private final double tp99;
private final double tp999;
public PerformanceSnapshot(MMAPCounter mmapCounter, int monitorInterval) {
tps = BigDecimal.valueOf(mmapCounter.getMmaCounter().getCount())
.divide(BigDecimal.valueOf(Math.max(monitorInterval, 1)), 1, RoundingMode.HALF_UP)
.doubleValue();
maxRt = mmapCounter.getMmaCounter().getMax();
minRt = mmapCounter.getMmaCounter().getMin();
avg = mmapCounter.getMmaCounter().getAvg();
tp50 = mmapCounter.getSnapshot().getMedian();
tp75 = mmapCounter.getSnapshot().get75thPercentile();
tp90 = mmapCounter.getSnapshot().getValue(0.9);
tp95 = mmapCounter.getSnapshot().get95thPercentile();
tp99 = mmapCounter.getSnapshot().get99thPercentile();
tp999 = mmapCounter.getSnapshot().get999thPercentile();
}
}
}
|
long currentMillis = System.currentTimeMillis();
int intervalTs = (int) (currentMillis - lastRefreshMillis.get()) / 1000;
val performanceSnapshot = new PerformanceSnapshot(mmapCounter, intervalTs);
reset(currentMillis);
return performanceSnapshot;
| 554
| 79
| 633
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/monitor/collector/LogCollector.java
|
LogCollector
|
collect
|
class LogCollector extends AbstractCollector {
@Override
public void collect(ThreadPoolStats threadPoolStats) {<FILL_FUNCTION_BODY>}
@Override
public String type() {
return CollectorTypeEnum.LOGGING.name().toLowerCase();
}
}
|
String metrics = JsonUtil.toJson(threadPoolStats);
if (LogHelper.getMonitorLogger() == null) {
log.error("Cannot find monitor logger...");
return;
}
LogHelper.getMonitorLogger().info("{}", metrics);
| 76
| 67
| 143
|
<methods>public non-sealed void <init>() ,public boolean support(java.lang.String) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/monitor/collector/MicroMeterCollector.java
|
MicroMeterCollector
|
collect
|
class MicroMeterCollector extends AbstractCollector {
/**
* Prefix used for all dtp metric names.
*/
public static final String DTP_METRIC_NAME_PREFIX = "thread.pool";
public static final String POOL_NAME_TAG = DTP_METRIC_NAME_PREFIX + ".name";
public static final String POOL_ALIAS_TAG = DTP_METRIC_NAME_PREFIX + ".alias";
public static final String APP_NAME_TAG = "app.name";
private static final Map<String, ThreadPoolStats> GAUGE_CACHE = new ConcurrentHashMap<>();
@Override
public void collect(ThreadPoolStats threadPoolStats) {<FILL_FUNCTION_BODY>}
@Override
public String type() {
return CollectorTypeEnum.MICROMETER.name().toLowerCase();
}
public void gauge(ThreadPoolStats poolStats) {
Iterable<Tag> tags = getTags(poolStats);
Metrics.gauge(metricName("core.size"), tags, poolStats, ThreadPoolStats::getCorePoolSize);
Metrics.gauge(metricName("maximum.size"), tags, poolStats, ThreadPoolStats::getMaximumPoolSize);
Metrics.gauge(metricName("current.size"), tags, poolStats, ThreadPoolStats::getPoolSize);
Metrics.gauge(metricName("largest.size"), tags, poolStats, ThreadPoolStats::getLargestPoolSize);
Metrics.gauge(metricName("active.count"), tags, poolStats, ThreadPoolStats::getActiveCount);
Metrics.gauge(metricName("task.count"), tags, poolStats, ThreadPoolStats::getTaskCount);
Metrics.gauge(metricName("completed.task.count"), tags, poolStats, ThreadPoolStats::getCompletedTaskCount);
Metrics.gauge(metricName("wait.task.count"), tags, poolStats, ThreadPoolStats::getWaitTaskCount);
Metrics.gauge(metricName("queue.size"), tags, poolStats, ThreadPoolStats::getQueueSize);
Metrics.gauge(metricName("queue.capacity"), tags, poolStats, ThreadPoolStats::getQueueCapacity);
Metrics.gauge(metricName("queue.remaining.capacity"), tags, poolStats, ThreadPoolStats::getQueueRemainingCapacity);
Metrics.gauge(metricName("reject.count"), tags, poolStats, ThreadPoolStats::getRejectCount);
Metrics.gauge(metricName("run.timeout.count"), tags, poolStats, ThreadPoolStats::getRunTimeoutCount);
Metrics.gauge(metricName("queue.timeout.count"), tags, poolStats, ThreadPoolStats::getQueueTimeoutCount);
Metrics.gauge(metricName("tps"), tags, poolStats, ThreadPoolStats::getTps);
Metrics.gauge(metricName("completed.task.time.avg"), tags, poolStats, ThreadPoolStats::getAvg);
Metrics.gauge(metricName("completed.task.time.max"), tags, poolStats, ThreadPoolStats::getMaxRt);
Metrics.gauge(metricName("completed.task.time.min"), tags, poolStats, ThreadPoolStats::getMinRt);
Metrics.gauge(metricName("completed.task.time.tp50"), tags, poolStats, ThreadPoolStats::getTp50);
Metrics.gauge(metricName("completed.task.time.tp75"), tags, poolStats, ThreadPoolStats::getTp75);
Metrics.gauge(metricName("completed.task.time.tp90"), tags, poolStats, ThreadPoolStats::getTp90);
Metrics.gauge(metricName("completed.task.time.tp95"), tags, poolStats, ThreadPoolStats::getTp95);
Metrics.gauge(metricName("completed.task.time.tp99"), tags, poolStats, ThreadPoolStats::getTp99);
Metrics.gauge(metricName("completed.task.time.tp999"), tags, poolStats, ThreadPoolStats::getTp999);
}
private static String metricName(String name) {
return String.join(".", DTP_METRIC_NAME_PREFIX, name);
}
private Iterable<Tag> getTags(ThreadPoolStats poolStats) {
List<Tag> tags = new ArrayList<>(3);
tags.add(Tag.of(POOL_NAME_TAG, poolStats.getPoolName()));
tags.add(Tag.of(APP_NAME_TAG, CommonUtil.getInstance().getServiceName()));
// https://github.com/dromara/dynamic-tp/issues/359
tags.add(Tag.of(POOL_ALIAS_TAG, Optional.ofNullable(poolStats.getPoolAliasName()).orElse(poolStats.getPoolName())));
return tags;
}
}
|
// metrics must be held with a strong reference, even though it is never referenced within this class
ThreadPoolStats oldStats = GAUGE_CACHE.get(threadPoolStats.getPoolName());
if (Objects.isNull(oldStats)) {
GAUGE_CACHE.put(threadPoolStats.getPoolName(), threadPoolStats);
} else {
BeanUtils.copyProperties(threadPoolStats, oldStats);
}
gauge(GAUGE_CACHE.get(threadPoolStats.getPoolName()));
| 1,246
| 133
| 1,379
|
<methods>public non-sealed void <init>() ,public boolean support(java.lang.String) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/monitor/collector/jmx/JMXCollector.java
|
JMXCollector
|
collect
|
class JMXCollector extends AbstractCollector {
public static final String DTP_METRIC_NAME_PREFIX = "dtp.thread.pool";
/**
* thread pool stats map
*/
private static final Map<String, ThreadPoolStats> GAUGE_CACHE = new ConcurrentHashMap<>();
@Override
public void collect(ThreadPoolStats threadPoolStats) {<FILL_FUNCTION_BODY>}
@Override
public String type() {
return CollectorTypeEnum.JMX.name().toLowerCase();
}
}
|
if (GAUGE_CACHE.containsKey(threadPoolStats.getPoolName())) {
ThreadPoolStats poolStats = GAUGE_CACHE.get(threadPoolStats.getPoolName());
BeanUtils.copyProperties(threadPoolStats, poolStats);
} else {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName(DTP_METRIC_NAME_PREFIX + ":name=" + threadPoolStats.getPoolName());
ThreadPoolStatsJMX stats = new ThreadPoolStatsJMX(threadPoolStats);
server.registerMBean(stats, name);
} catch (JMException e) {
log.error("collect thread pool stats error", e);
}
GAUGE_CACHE.put(threadPoolStats.getPoolName(), threadPoolStats);
}
| 149
| 220
| 369
|
<methods>public non-sealed void <init>() ,public boolean support(java.lang.String) <variables>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/DtpLarkNotifier.java
|
DtpLarkNotifier
|
formatReceivers
|
class DtpLarkNotifier extends AbstractDtpNotifier {
public DtpLarkNotifier(Notifier notifier) {
super(notifier);
}
@Override
public String platform() {
return NotifyPlatformEnum.LARK.name().toLowerCase();
}
@Override
protected String getNoticeTemplate() {
return LarkNotifyConst.LARK_CHANGE_NOTICE_JSON_STR;
}
@Override
protected String getAlarmTemplate() {
return LarkNotifyConst.LARK_ALARM_JSON_STR;
}
@Override
protected Pair<String, String> getColors() {
return new ImmutablePair<>(LarkNotifyConst.WARNING_COLOR, LarkNotifyConst.COMMENT_COLOR);
}
@Override
protected String formatReceivers(String receives) {<FILL_FUNCTION_BODY>}
}
|
return Arrays.stream(receives.split(","))
.map(r -> StringUtils.startsWith(r, LARK_OPENID_PREFIX) ?
String.format(LARK_AT_FORMAT_OPENID, r) : String.format(LARK_AT_FORMAT_USERNAME, r))
.collect(Collectors.joining(" "));
| 239
| 99
| 338
|
<methods>public void sendAlarmMsg(org.dromara.dynamictp.common.entity.NotifyPlatform, org.dromara.dynamictp.common.em.NotifyItemEnum) ,public void sendChangeMsg(org.dromara.dynamictp.common.entity.NotifyPlatform, org.dromara.dynamictp.common.entity.TpMainFields, List<java.lang.String>) <variables>protected org.dromara.dynamictp.common.notifier.Notifier notifier
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/DtpWechatNotifier.java
|
DtpWechatNotifier
|
formatReceivers
|
class DtpWechatNotifier extends AbstractDtpNotifier {
public DtpWechatNotifier(Notifier notifier) {
super(notifier);
}
@Override
public String platform() {
return NotifyPlatformEnum.WECHAT.name().toLowerCase();
}
@Override
protected String getNoticeTemplate() {
return WechatNotifyConst.WECHAT_CHANGE_NOTICE_TEMPLATE;
}
@Override
protected String getAlarmTemplate() {
return WechatNotifyConst.WECHAT_ALARM_TEMPLATE;
}
@Override
protected Pair<String, String> getColors() {
return new ImmutablePair<>(WechatNotifyConst.WARNING_COLOR, WechatNotifyConst.COMMENT_COLOR);
}
@Override
protected String formatReceivers(String receives) {<FILL_FUNCTION_BODY>}
}
|
return Arrays.stream(StringUtils.split(receives, ','))
.map(receiver -> "<@" + receiver + ">")
.collect(Collectors.joining(","));
| 241
| 55
| 296
|
<methods>public void sendAlarmMsg(org.dromara.dynamictp.common.entity.NotifyPlatform, org.dromara.dynamictp.common.em.NotifyItemEnum) ,public void sendChangeMsg(org.dromara.dynamictp.common.entity.NotifyPlatform, org.dromara.dynamictp.common.entity.TpMainFields, List<java.lang.String>) <variables>protected org.dromara.dynamictp.common.notifier.Notifier notifier
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/alarm/AlarmCounter.java
|
AlarmCounter
|
calcCurrentValue
|
class AlarmCounter {
private static final Map<String, AlarmInfo> ALARM_INFO_CACHE = new ConcurrentHashMap<>();
private AlarmCounter() { }
public static void init(String threadPoolName, String notifyItemType) {
String key = buildKey(threadPoolName, notifyItemType);
val alarmInfo = new AlarmInfo().setNotifyItem(NotifyItemEnum.of(notifyItemType));
ALARM_INFO_CACHE.putIfAbsent(key, alarmInfo);
}
public static AlarmInfo getAlarmInfo(String threadPoolName, String notifyItemType) {
String key = buildKey(threadPoolName, notifyItemType);
return ALARM_INFO_CACHE.get(key);
}
public static String getCount(String threadPoolName, String notifyItemType) {
String key = buildKey(threadPoolName, notifyItemType);
val alarmInfo = ALARM_INFO_CACHE.get(key);
if (Objects.nonNull(alarmInfo)) {
return String.valueOf(alarmInfo.getCount());
}
return UNKNOWN;
}
public static void reset(String threadPoolName, String notifyItemType) {
String key = buildKey(threadPoolName, notifyItemType);
var alarmInfo = ALARM_INFO_CACHE.get(key);
alarmInfo.reset();
}
public static void incAlarmCounter(String threadPoolName, String notifyItemType) {
String key = buildKey(threadPoolName, notifyItemType);
var alarmInfo = ALARM_INFO_CACHE.get(key);
if (Objects.nonNull(alarmInfo)) {
alarmInfo.incCounter();
}
}
public static int calcCurrentValue(ExecutorWrapper wrapper, NotifyItemEnum itemEnum) {<FILL_FUNCTION_BODY>}
private static String buildKey(String threadPoolName, String notifyItemType) {
return threadPoolName + ":" + notifyItemType;
}
}
|
val executor = wrapper.getExecutor();
switch (itemEnum) {
case CAPACITY:
return (int) (NumberUtil.div(executor.getQueueSize(), executor.getQueueCapacity(), 2) * 100);
case LIVENESS:
return (int) (NumberUtil.div(executor.getActiveCount(), executor.getMaximumPoolSize(), 2) * 100);
case REJECT:
case RUN_TIMEOUT:
case QUEUE_TIMEOUT:
return Integer.parseInt(getCount(wrapper.getThreadPoolName(), itemEnum.getValue()));
default:
return 0;
}
| 517
| 172
| 689
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/alarm/AlarmLimiter.java
|
AlarmLimiter
|
initAlarmLimiter
|
class AlarmLimiter {
private static final Map<String, Cache<String, String>> ALARM_LIMITER = new ConcurrentHashMap<>();
private AlarmLimiter() { }
public static void initAlarmLimiter(String threadPoolName, NotifyItem notifyItem) {<FILL_FUNCTION_BODY>}
public static void putVal(String threadPoolName, String type) {
String key = genKey(threadPoolName, type);
ALARM_LIMITER.get(key).put(type, type);
}
public static String getAlarmLimitInfo(String key, String type) {
val cache = ALARM_LIMITER.get(key);
if (Objects.isNull(cache)) {
return null;
}
return cache.getIfPresent(type);
}
public static boolean ifAlarm(String threadPoolName, String type) {
String key = genKey(threadPoolName, type);
return StringUtils.isBlank(getAlarmLimitInfo(key, type));
}
public static String genKey(String threadPoolName, String type) {
return threadPoolName + ":" + type;
}
}
|
if (NotifyItemEnum.CHANGE.getValue().equalsIgnoreCase(notifyItem.getType())) {
return;
}
String key = genKey(threadPoolName, notifyItem.getType());
Cache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(notifyItem.getInterval(), TimeUnit.SECONDS)
.build();
ALARM_LIMITER.put(key, cache);
| 304
| 112
| 416
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/chain/filter/AlarmBaseFilter.java
|
AlarmBaseFilter
|
doFilter
|
class AlarmBaseFilter implements NotifyFilter {
private static final Object SEND_LOCK = new Object();
@Override
public void doFilter(BaseNotifyCtx context, Invoker<BaseNotifyCtx> nextInvoker) {<FILL_FUNCTION_BODY>}
private boolean satisfyBaseCondition(NotifyItem notifyItem, ExecutorWrapper executor) {
return executor.isNotifyEnabled()
&& notifyItem.isEnabled()
&& CollectionUtils.isNotEmpty(notifyItem.getPlatformIds());
}
@Override
public int getOrder() {
return 0;
}
}
|
val executorWrapper = context.getExecutorWrapper();
val notifyItem = context.getNotifyItem();
if (Objects.isNull(notifyItem) || !satisfyBaseCondition(notifyItem, executorWrapper)) {
return;
}
boolean ifAlarm = AlarmLimiter.ifAlarm(executorWrapper.getThreadPoolName(), notifyItem.getType());
if (!ifAlarm) {
log.debug("DynamicTp notify, alarm limit, threadPoolName: {}, notifyItem: {}",
executorWrapper.getThreadPoolName(), notifyItem.getType());
return;
}
if (!AlarmManager.checkThreshold(executorWrapper, context.getNotifyItemEnum(), notifyItem)) {
return;
}
synchronized (SEND_LOCK) {
// recheck alarm limit.
ifAlarm = AlarmLimiter.ifAlarm(executorWrapper.getThreadPoolName(), notifyItem.getType());
if (!ifAlarm) {
log.warn("DynamicTp notify, concurrent send, alarm limit, threadPoolName: {}, notifyItem: {}",
executorWrapper.getThreadPoolName(), notifyItem.getType());
return;
}
AlarmLimiter.putVal(executorWrapper.getThreadPoolName(), notifyItem.getType());
}
nextInvoker.invoke(context);
| 157
| 341
| 498
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/chain/filter/NoticeBaseFilter.java
|
NoticeBaseFilter
|
doFilter
|
class NoticeBaseFilter implements NotifyFilter {
@Override
public void doFilter(BaseNotifyCtx context, Invoker<BaseNotifyCtx> nextInvoker) {<FILL_FUNCTION_BODY>}
private boolean satisfyBaseCondition(NotifyItem notifyItem, ExecutorWrapper executor) {
return executor.isNotifyEnabled()
&& notifyItem.isEnabled()
&& CollectionUtils.isNotEmpty(notifyItem.getPlatformIds());
}
@Override
public int getOrder() {
return 0;
}
}
|
val executorWrapper = context.getExecutorWrapper();
val notifyItem = context.getNotifyItem();
if (Objects.isNull(notifyItem) || !satisfyBaseCondition(notifyItem, executorWrapper)) {
log.debug("DynamicTp notify, no platforms configured or notification is not enabled, threadPoolName: {}",
executorWrapper.getThreadPoolName());
return;
}
nextInvoker.invoke(context);
| 141
| 111
| 252
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/chain/invoker/AlarmInvoker.java
|
AlarmInvoker
|
invoke
|
class AlarmInvoker implements Invoker<BaseNotifyCtx> {
@Override
public void invoke(BaseNotifyCtx context) {<FILL_FUNCTION_BODY>}
}
|
val alarmCtx = (AlarmCtx) context;
val executorWrapper = alarmCtx.getExecutorWrapper();
val notifyItem = alarmCtx.getNotifyItem();
val alarmInfo = AlarmCounter.getAlarmInfo(executorWrapper.getThreadPoolName(), notifyItem.getType());
alarmCtx.setAlarmInfo(alarmInfo);
try {
DtpNotifyCtxHolder.set(context);
NotifierHandler.getInstance().sendAlarm(NotifyItemEnum.of(notifyItem.getType()));
AlarmCounter.reset(executorWrapper.getThreadPoolName(), notifyItem.getType());
} finally {
DtpNotifyCtxHolder.remove();
}
| 50
| 181
| 231
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/chain/invoker/NoticeInvoker.java
|
NoticeInvoker
|
invoke
|
class NoticeInvoker implements Invoker<BaseNotifyCtx> {
@Override
public void invoke(BaseNotifyCtx context) {<FILL_FUNCTION_BODY>}
}
|
try {
DtpNotifyCtxHolder.set(context);
val noticeCtx = (NoticeCtx) context;
NotifierHandler.getInstance().sendNotice(noticeCtx.getOldFields(), noticeCtx.getDiffs());
} finally {
DtpNotifyCtxHolder.remove();
}
| 49
| 83
| 132
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/manager/AlarmManager.java
|
AlarmManager
|
checkThreshold
|
class AlarmManager {
private static final ExecutorService ALARM_EXECUTOR = ThreadPoolBuilder.newBuilder()
.threadFactory("dtp-alarm")
.corePoolSize(1)
.maximumPoolSize(1)
.workQueue(LINKED_BLOCKING_QUEUE.getName(), 2000)
.rejectedExecutionHandler(RejectedTypeEnum.DISCARD_OLDEST_POLICY.getName())
.rejectEnhanced(false)
.taskWrappers(TaskWrappers.getInstance().getByNames(Sets.newHashSet("mdc")))
.buildDynamic();
private static final InvokerChain<BaseNotifyCtx> ALARM_INVOKER_CHAIN;
static {
ALARM_INVOKER_CHAIN = NotifyFilterBuilder.getAlarmInvokerChain();
}
private AlarmManager() { }
public static void initAlarm(String poolName, List<NotifyItem> notifyItems) {
notifyItems.forEach(x -> initAlarm(poolName, x));
}
public static void initAlarm(String poolName, NotifyItem notifyItem) {
AlarmLimiter.initAlarmLimiter(poolName, notifyItem);
AlarmCounter.init(poolName, notifyItem.getType());
}
public static void tryAlarmAsync(ExecutorWrapper executorWrapper, NotifyItemEnum notifyType, Runnable runnable) {
preAlarm(runnable);
try {
ALARM_EXECUTOR.execute(() -> doTryAlarm(executorWrapper, notifyType));
} finally {
postAlarm(runnable);
}
}
public static void tryAlarmAsync(ExecutorWrapper executorWrapper, List<NotifyItemEnum> notifyTypes) {
ALARM_EXECUTOR.execute(() -> notifyTypes.forEach(x -> doTryAlarm(executorWrapper, x)));
}
public static void doTryAlarm(ExecutorWrapper executorWrapper, NotifyItemEnum notifyType) {
AlarmCounter.incAlarmCounter(executorWrapper.getThreadPoolName(), notifyType.getValue());
NotifyHelper.getNotifyItem(executorWrapper, notifyType).ifPresent(notifyItem -> {
val alarmCtx = new AlarmCtx(executorWrapper, notifyItem);
ALARM_INVOKER_CHAIN.proceed(alarmCtx);
});
}
public static boolean checkThreshold(ExecutorWrapper executor, NotifyItemEnum notifyType, NotifyItem notifyItem) {<FILL_FUNCTION_BODY>}
public static void destroy() {
ALARM_EXECUTOR.shutdownNow();
}
private static boolean checkLiveness(ExecutorWrapper executorWrapper, NotifyItem notifyItem) {
val executor = executorWrapper.getExecutor();
int maximumPoolSize = executor.getMaximumPoolSize();
double div = NumberUtil.div(executor.getActiveCount(), maximumPoolSize, 2) * 100;
return div >= notifyItem.getThreshold();
}
private static boolean checkCapacity(ExecutorWrapper executorWrapper, NotifyItem notifyItem) {
val executor = executorWrapper.getExecutor();
if (executor.getQueueSize() <= 0) {
return false;
}
double div = NumberUtil.div(executor.getQueueSize(), executor.getQueueCapacity(), 2) * 100;
return div >= notifyItem.getThreshold();
}
private static boolean checkWithAlarmInfo(ExecutorWrapper executorWrapper, NotifyItem notifyItem) {
AlarmInfo alarmInfo = AlarmCounter.getAlarmInfo(executorWrapper.getThreadPoolName(), notifyItem.getType());
return alarmInfo.getCount() >= notifyItem.getThreshold();
}
private static void preAlarm(Runnable runnable) {
if (runnable instanceof DtpRunnable) {
MDC.put(TRACE_ID, ((DtpRunnable) runnable).getTraceId());
}
}
private static void postAlarm(Runnable runnable) {
if (runnable instanceof DtpRunnable) {
MDC.remove(TRACE_ID);
}
}
}
|
switch (notifyType) {
case CAPACITY:
return checkCapacity(executor, notifyItem);
case LIVENESS:
return checkLiveness(executor, notifyItem);
case REJECT:
case RUN_TIMEOUT:
case QUEUE_TIMEOUT:
return checkWithAlarmInfo(executor, notifyItem);
default:
log.error("Unsupported alarm type [{}]", notifyType);
return false;
}
| 1,095
| 123
| 1,218
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/manager/NoticeManager.java
|
NoticeManager
|
doTryNotice
|
class NoticeManager {
private static final ExecutorService NOTICE_EXECUTOR = ThreadPoolBuilder.newBuilder()
.threadFactory("dtp-notify")
.corePoolSize(1)
.maximumPoolSize(1)
.workQueue(LINKED_BLOCKING_QUEUE.getName(), 100)
.rejectedExecutionHandler(RejectedTypeEnum.DISCARD_OLDEST_POLICY.getName())
.buildCommon();
private NoticeManager() { }
private static final InvokerChain<BaseNotifyCtx> NOTICE_INVOKER_CHAIN;
static {
NOTICE_INVOKER_CHAIN = NotifyFilterBuilder.getCommonInvokerChain();
}
public static void tryNoticeAsync(ExecutorWrapper executor, TpMainFields oldFields, List<String> diffKeys) {
NOTICE_EXECUTOR.execute(() -> doTryNotice(executor, oldFields, diffKeys));
}
public static void doTryNotice(ExecutorWrapper executor, TpMainFields oldFields, List<String> diffKeys) {<FILL_FUNCTION_BODY>}
public static void destroy() {
NOTICE_EXECUTOR.shutdownNow();
}
}
|
NotifyHelper.getNotifyItem(executor, CHANGE).ifPresent(notifyItem -> {
val noticeCtx = new NoticeCtx(executor, notifyItem, oldFields, diffKeys);
NOTICE_INVOKER_CHAIN.proceed(noticeCtx);
});
| 315
| 76
| 391
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/manager/NotifyFilterBuilder.java
|
NotifyFilterBuilder
|
getAlarmInvokerChain
|
class NotifyFilterBuilder {
private NotifyFilterBuilder() { }
public static InvokerChain<BaseNotifyCtx> getAlarmInvokerChain() {<FILL_FUNCTION_BODY>}
public static InvokerChain<BaseNotifyCtx> getCommonInvokerChain() {
val filters = ApplicationContextHolder.getBeansOfType(NotifyFilter.class);
Collection<NotifyFilter> noticeFilters = Lists.newArrayList(filters.values());
noticeFilters.add(new NoticeBaseFilter());
noticeFilters = noticeFilters.stream()
.filter(x -> x.supports(NotifyTypeEnum.COMMON))
.sorted(Comparator.comparing(Filter::getOrder))
.collect(Collectors.toList());
return InvokerChainFactory.buildInvokerChain(new NoticeInvoker(), noticeFilters.toArray(new NotifyFilter[0]));
}
}
|
val filters = ApplicationContextHolder.getBeansOfType(NotifyFilter.class);
Collection<NotifyFilter> alarmFilters = Lists.newArrayList(filters.values());
alarmFilters.add(new AlarmBaseFilter());
alarmFilters = alarmFilters.stream()
.filter(x -> x.supports(NotifyTypeEnum.ALARM))
.sorted(Comparator.comparing(Filter::getOrder))
.collect(Collectors.toList());
return InvokerChainFactory.buildInvokerChain(new AlarmInvoker(), alarmFilters.toArray(new NotifyFilter[0]));
| 232
| 158
| 390
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/notifier/manager/NotifyHelper.java
|
NotifyHelper
|
fillPlatforms
|
class NotifyHelper {
private static final List<String> COMMON_ALARM_KEYS = Lists.newArrayList("alarmType", "alarmValue");
private static final Set<String> LIVENESS_ALARM_KEYS = Sets.newHashSet(
"corePoolSize", "maximumPoolSize", "poolSize", "activeCount");
private static final Set<String> CAPACITY_ALARM_KEYS = Sets.newHashSet(
"queueType", "queueCapacity", "queueSize", "queueRemaining");
private static final Set<String> REJECT_ALARM_KEYS = Sets.newHashSet("rejectType", "rejectCount");
private static final Set<String> RUN_TIMEOUT_ALARM_KEYS = Sets.newHashSet("runTimeoutCount");
private static final Set<String> QUEUE_TIMEOUT_ALARM_KEYS = Sets.newHashSet("queueTimeoutCount");
private static final Set<String> ALL_ALARM_KEYS;
private static final Map<String, Set<String>> ALARM_KEYS = Maps.newHashMap();
static {
ALARM_KEYS.put(LIVENESS.name(), LIVENESS_ALARM_KEYS);
ALARM_KEYS.put(CAPACITY.name(), CAPACITY_ALARM_KEYS);
ALARM_KEYS.put(REJECT.name(), REJECT_ALARM_KEYS);
ALARM_KEYS.put(RUN_TIMEOUT.name(), RUN_TIMEOUT_ALARM_KEYS);
ALARM_KEYS.put(QUEUE_TIMEOUT.name(), QUEUE_TIMEOUT_ALARM_KEYS);
ALL_ALARM_KEYS = ALARM_KEYS.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
ALL_ALARM_KEYS.addAll(COMMON_ALARM_KEYS);
}
private NotifyHelper() {
}
public static Set<String> getAllAlarmKeys() {
return ALL_ALARM_KEYS;
}
public static Set<String> getAlarmKeys(NotifyItemEnum notifyItemEnum) {
val keys = ALARM_KEYS.get(notifyItemEnum.name());
keys.addAll(COMMON_ALARM_KEYS);
return keys;
}
public static Optional<NotifyItem> getNotifyItem(ExecutorWrapper executor, NotifyItemEnum notifyType) {
if (CollectionUtils.isEmpty(executor.getNotifyItems())) {
return Optional.empty();
}
return executor.getNotifyItems().stream()
.filter(x -> notifyType.getValue().equalsIgnoreCase(x.getType()))
.findFirst();
}
public static void fillPlatforms(List<String> platformIds,
List<NotifyPlatform> platforms,
List<NotifyItem> notifyItems) {<FILL_FUNCTION_BODY>}
public static Optional<NotifyPlatform> getPlatform(String platformId) {
Map<String, NotifyPlatform> platformMap = getAllPlatforms();
return Optional.ofNullable(platformMap.get(platformId));
}
public static Map<String, NotifyPlatform> getAllPlatforms() {
val dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
if (CollectionUtils.isEmpty(dtpProperties.getPlatforms())) {
return Collections.emptyMap();
}
return StreamUtil.toMap(dtpProperties.getPlatforms(), NotifyPlatform::getPlatformId);
}
public static void initNotify(DtpExecutor executor) {
val dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
val platforms = dtpProperties.getPlatforms();
if (CollectionUtils.isEmpty(platforms)) {
executor.setNotifyItems(Lists.newArrayList());
executor.setPlatformIds(Lists.newArrayList());
log.warn("DynamicTp notify, no notify platforms configured for [{}]", executor.getThreadPoolName());
return;
}
if (CollectionUtils.isEmpty(executor.getNotifyItems())) {
log.warn("DynamicTp notify, no notify items configured for [{}]", executor.getThreadPoolName());
return;
}
fillPlatforms(executor.getPlatformIds(), platforms, executor.getNotifyItems());
AlarmManager.initAlarm(executor.getThreadPoolName(), executor.getNotifyItems());
}
public static void updateNotifyInfo(ExecutorWrapper executorWrapper,
TpExecutorProps props,
List<NotifyPlatform> platforms) {
// update notify items
val allNotifyItems = mergeAllNotifyItems(props.getNotifyItems());
refreshNotify(executorWrapper.getThreadPoolName(),
props.getPlatformIds(),
platforms,
executorWrapper.getNotifyItems(),
allNotifyItems);
executorWrapper.setNotifyItems(allNotifyItems);
executorWrapper.setPlatformIds(props.getPlatformIds());
executorWrapper.setNotifyEnabled(props.isNotifyEnabled());
}
public static void updateNotifyInfo(DtpExecutor executor, DtpExecutorProps props, List<NotifyPlatform> platforms) {
// update notify items
val allNotifyItems = mergeAllNotifyItems(props.getNotifyItems());
refreshNotify(executor.getThreadPoolName(),
props.getPlatformIds(),
platforms,
executor.getNotifyItems(),
allNotifyItems);
executor.setNotifyItems(allNotifyItems);
executor.setPlatformIds(props.getPlatformIds());
executor.setNotifyEnabled(props.isNotifyEnabled());
}
private static void refreshNotify(String poolName,
List<String> platformIds,
List<NotifyPlatform> platforms,
List<NotifyItem> oldNotifyItems,
List<NotifyItem> newNotifyItems) {
fillPlatforms(platformIds, platforms, newNotifyItems);
Map<String, NotifyItem> oldNotifyItemMap = StreamUtil.toMap(oldNotifyItems, NotifyItem::getType);
newNotifyItems.forEach(x -> {
NotifyItem oldNotifyItem = oldNotifyItemMap.get(x.getType());
if (Objects.nonNull(oldNotifyItem) && oldNotifyItem.getInterval() == x.getInterval()) {
return;
}
AlarmManager.initAlarm(poolName, x);
});
}
}
|
if (CollectionUtils.isEmpty(platforms) || CollectionUtils.isEmpty(notifyItems)) {
return;
}
List<String> globalPlatformIds = StreamUtil.fetchProperty(platforms, NotifyPlatform::getPlatformId);
// notifyItem > executor > global
notifyItems.forEach(n -> {
if (CollectionUtils.isNotEmpty(n.getPlatformIds())) {
// intersection of notifyItem and global
n.setPlatformIds((List<String>) CollectionUtils.intersection(globalPlatformIds, n.getPlatformIds()));
} else if (CollectionUtils.isNotEmpty(platformIds)) {
n.setPlatformIds((List<String>) CollectionUtils.intersection(globalPlatformIds, platformIds));
} else {
n.setPlatformIds(globalPlatformIds);
}
});
| 1,676
| 202
| 1,878
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/refresher/AbstractRefresher.java
|
AbstractRefresher
|
refresh
|
class AbstractRefresher implements Refresher, EnvironmentAware {
protected final DtpProperties dtpProperties;
protected Environment environment;
protected AbstractRefresher(DtpProperties dtpProperties) {
this.dtpProperties = dtpProperties;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void refresh(String content, ConfigFileTypeEnum fileType) {
if (StringUtils.isBlank(content) || Objects.isNull(fileType)) {
log.warn("DynamicTp refresh, empty content or null fileType.");
return;
}
try {
val configHandler = ConfigHandler.getInstance();
val properties = configHandler.parseConfig(content, fileType);
refresh(properties);
} catch (IOException e) {
log.error("DynamicTp refresh error, content: {}, fileType: {}", content, fileType, e);
}
}
protected void refresh(Map<Object, Object> properties) {<FILL_FUNCTION_BODY>}
protected void refresh(Environment environment) {
BinderHelper.bindDtpProperties(environment, dtpProperties);
doRefresh(dtpProperties);
}
protected void doRefresh(DtpProperties properties) {
DtpRegistry.refresh(properties);
publishEvent(properties);
}
protected boolean needRefresh(Set<String> changedKeys) {
if (CollectionUtils.isEmpty(changedKeys)) {
return false;
}
changedKeys = changedKeys.stream()
.filter(str -> str.startsWith(MAIN_PROPERTIES_PREFIX))
.collect(Collectors.toSet());
return CollectionUtils.isNotEmpty(changedKeys);
}
private void publishEvent(DtpProperties dtpProperties) {
RefreshEvent event = new RefreshEvent(this, dtpProperties);
ApplicationContextHolder.publishEvent(event);
}
}
|
if (MapUtils.isEmpty(properties)) {
log.warn("DynamicTp refresh, empty properties.");
return;
}
BinderHelper.bindDtpProperties(properties, dtpProperties);
doRefresh(dtpProperties);
| 500
| 63
| 563
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/reject/RejectHandlerGetter.java
|
RejectHandlerGetter
|
buildRejectedHandler
|
class RejectHandlerGetter {
private RejectHandlerGetter() { }
public static RejectedExecutionHandler buildRejectedHandler(String name) {<FILL_FUNCTION_BODY>}
public static RejectedExecutionHandler getProxy(String name) {
return getProxy(buildRejectedHandler(name));
}
public static RejectedExecutionHandler getProxy(RejectedExecutionHandler handler) {
return (RejectedExecutionHandler) Proxy
.newProxyInstance(handler.getClass().getClassLoader(),
new Class[]{RejectedExecutionHandler.class},
new RejectedInvocationHandler(handler));
}
}
|
if (Objects.equals(name, ABORT_POLICY.getName())) {
return new ThreadPoolExecutor.AbortPolicy();
} else if (Objects.equals(name, CALLER_RUNS_POLICY.getName())) {
return new ThreadPoolExecutor.CallerRunsPolicy();
} else if (Objects.equals(name, DISCARD_OLDEST_POLICY.getName())) {
return new ThreadPoolExecutor.DiscardOldestPolicy();
} else if (Objects.equals(name, DISCARD_POLICY.getName())) {
return new ThreadPoolExecutor.DiscardPolicy();
}
List<RejectedExecutionHandler> loadedHandlers = ExtensionServiceLoader.get(RejectedExecutionHandler.class);
for (RejectedExecutionHandler handler : loadedHandlers) {
String handlerName = handler.getClass().getSimpleName();
if (name.equalsIgnoreCase(handlerName)) {
return handler;
}
}
log.error("Cannot find specified rejectedHandler {}", name);
throw new DtpException("Cannot find specified rejectedHandler " + name);
| 156
| 272
| 428
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/reject/RejectedInvocationHandler.java
|
RejectedInvocationHandler
|
invoke
|
class RejectedInvocationHandler implements InvocationHandler {
private final Object target;
public RejectedInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
/**
* Do sth before reject.
*
* @param runnable the runnable
* @param executor ThreadPoolExecutor instance
*/
private void beforeReject(Runnable runnable, Executor executor) {
AwareManager.beforeReject(runnable, executor);
}
/**
* Do sth after reject.
*
* @param runnable the runnable
* @param executor ThreadPoolExecutor instance
*/
private void afterReject(Runnable runnable, Executor executor) {
AwareManager.afterReject(runnable, executor);
}
}
|
beforeReject((Runnable) args[0], (Executor) args[1]);
try {
return method.invoke(target, args);
} catch (InvocationTargetException ex) {
throw ex.getCause();
} finally {
afterReject((Runnable) args[0], (Executor) args[1]);
}
| 251
| 89
| 340
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/DtpBaseBeanDefinitionRegistrar.java
|
DtpBaseBeanDefinitionRegistrar
|
registerBeanDefinitions
|
class DtpBaseBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
private static final String APPLICATION_CONTEXT_HOLDER = "dtpApplicationContextHolder";
private static final String HASHED_WHEEL_TIMER = "dtpHashedWheelTimer";
private static final String DTP_POST_PROCESSOR = "dtpPostProcessor";
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>}
private void registerHashedWheelTimer(BeanDefinitionRegistry registry) {
Object[] constructorArgs = new Object[] {
new NamedThreadFactory("dtp-runnable-timeout", true),
10,
TimeUnit.MILLISECONDS
};
SpringBeanHelper.registerIfAbsent(registry, HASHED_WHEEL_TIMER, HashedWheelTimer.class, constructorArgs);
}
}
|
registerHashedWheelTimer(registry);
SpringBeanHelper.registerIfAbsent(registry, APPLICATION_CONTEXT_HOLDER, ApplicationContextHolder.class);
// ApplicationContextHolder and HashedWheelTimer are required in DtpExecutor execute method, so they must be registered first
SpringBeanHelper.registerIfAbsent(registry, DTP_POST_PROCESSOR, DtpPostProcessor.class,
null, Lists.newArrayList(APPLICATION_CONTEXT_HOLDER, HASHED_WHEEL_TIMER));
| 242
| 137
| 379
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/DtpBeanDefinitionRegistrar.java
|
DtpBeanDefinitionRegistrar
|
buildPropertyValues
|
class DtpBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
DtpProperties dtpProperties = DtpProperties.getInstance();
BinderHelper.bindDtpProperties(environment, dtpProperties);
val executors = dtpProperties.getExecutors();
if (CollectionUtils.isEmpty(executors)) {
log.warn("DynamicTp registrar, no executors are configured.");
return;
}
executors.forEach(e -> {
Class<?> executorTypeClass = ExecutorType.getClass(e.getExecutorType());
Map<String, Object> propertyValues = buildPropertyValues(e);
Object[] args = buildConstructorArgs(executorTypeClass, e);
SpringBeanHelper.register(registry, e.getThreadPoolName(), executorTypeClass, propertyValues, args);
});
}
private Map<String, Object> buildPropertyValues(DtpExecutorProps props) {<FILL_FUNCTION_BODY>}
private Object[] buildConstructorArgs(Class<?> clazz, DtpExecutorProps props) {
BlockingQueue<Runnable> taskQueue;
if (clazz.equals(EagerDtpExecutor.class)) {
taskQueue = new TaskQueue(props.getQueueCapacity());
} else if (clazz.equals(PriorityDtpExecutor.class)) {
taskQueue = new PriorityBlockingQueue<>(props.getQueueCapacity(), PriorityDtpExecutor.getRunnableComparator());
} else {
taskQueue = buildLbq(props.getQueueType(),
props.getQueueCapacity(),
props.isFair(),
props.getMaxFreeMemory());
}
return new Object[]{
props.getCorePoolSize(),
props.getMaximumPoolSize(),
props.getKeepAliveTime(),
props.getUnit(),
taskQueue,
new NamedThreadFactory(props.getThreadNamePrefix()),
RejectHandlerGetter.buildRejectedHandler(props.getRejectedHandlerType())
};
}
}
|
Map<String, Object> propertyValues = Maps.newHashMap();
propertyValues.put(THREAD_POOL_NAME, props.getThreadPoolName());
propertyValues.put(THREAD_POOL_ALIAS_NAME, props.getThreadPoolAliasName());
propertyValues.put(ALLOW_CORE_THREAD_TIMEOUT, props.isAllowCoreThreadTimeOut());
propertyValues.put(WAIT_FOR_TASKS_TO_COMPLETE_ON_SHUTDOWN, props.isWaitForTasksToCompleteOnShutdown());
propertyValues.put(AWAIT_TERMINATION_SECONDS, props.getAwaitTerminationSeconds());
propertyValues.put(PRE_START_ALL_CORE_THREADS, props.isPreStartAllCoreThreads());
propertyValues.put(REJECT_HANDLER_TYPE, props.getRejectedHandlerType());
propertyValues.put(REJECT_ENHANCED, props.isRejectEnhanced());
propertyValues.put(RUN_TIMEOUT, props.getRunTimeout());
propertyValues.put(TRY_INTERRUPT_WHEN_TIMEOUT, props.isTryInterrupt());
propertyValues.put(QUEUE_TIMEOUT, props.getQueueTimeout());
val notifyItems = mergeAllNotifyItems(props.getNotifyItems());
propertyValues.put(NOTIFY_ITEMS, notifyItems);
propertyValues.put(PLATFORM_IDS, props.getPlatformIds());
propertyValues.put(NOTIFY_ENABLED, props.isNotifyEnabled());
val taskWrappers = TaskWrappers.getInstance().getByNames(props.getTaskWrapperNames());
propertyValues.put(TASK_WRAPPERS, taskWrappers);
propertyValues.put(PLUGIN_NAMES, props.getPluginNames());
propertyValues.put(AWARE_NAMES, props.getAwareNames());
return propertyValues;
| 572
| 481
| 1,053
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/DtpConfigurationSelector.java
|
DtpConfigurationSelector
|
selectImports
|
class DtpConfigurationSelector implements DeferredImportSelector, Ordered, EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public String[] selectImports(AnnotationMetadata metadata) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
|
if (!BooleanUtils.toBoolean(environment.getProperty(DTP_ENABLED_PROP, BooleanUtils.TRUE))) {
return new String[]{};
}
return new String[] {
DtpBaseBeanDefinitionRegistrar.class.getName(),
DtpBeanDefinitionRegistrar.class.getName(),
DtpBaseBeanConfiguration.class.getName()
};
| 116
| 93
| 209
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/DtpLifecycle.java
|
DtpLifecycle
|
stop
|
class DtpLifecycle implements SmartLifecycle {
private final AtomicBoolean running = new AtomicBoolean(false);
@Override
public void start() {
if (this.running.compareAndSet(false, true)) {
DtpRegistry.getAllExecutors().forEach((k, v) -> DtpLifecycleSupport.initialize(v));
}
}
@Override
public void stop() {<FILL_FUNCTION_BODY>}
@Override
public boolean isRunning() {
return this.running.get();
}
/**
* Compatible with lower versions of spring.
*
* @param callback callback
*/
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
/**
* Compatible with lower versions of spring.
*
* @return isAutoStartup
*/
@Override
public boolean isAutoStartup() {
return true;
}
/**
* Compatible with lower versions of spring.
*
* @return phase
*/
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
public void shutdownInternal() {
DtpMonitor.destroy();
AlarmManager.destroy();
NoticeManager.destroy();
SystemMetricManager.stop();
}
}
|
if (this.running.compareAndSet(true, false)) {
shutdownInternal();
DtpRegistry.getAllExecutors().forEach((k, v) -> DtpLifecycleSupport.destroy(v));
}
| 358
| 59
| 417
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/DtpPostProcessor.java
|
DtpPostProcessor
|
postProcessAfterInitialization
|
class DtpPostProcessor implements BeanPostProcessor, BeanFactoryAware, PriorityOrdered {
private static final String REGISTER_SOURCE = "beanPostProcessor";
private DefaultListableBeanFactory beanFactory;
/**
* Compatible with lower versions of Spring.
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use
* @throws BeansException in case of errors
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
private Object registerAndReturnDtp(Object bean) {
DtpExecutor dtpExecutor = (DtpExecutor) bean;
Object[] args = ConstructorUtil.buildTpExecutorConstructorArgs(dtpExecutor);
Class<?>[] argTypes = ConstructorUtil.buildTpExecutorConstructorArgTypes();
Set<String> pluginNames = dtpExecutor.getPluginNames();
val enhancedBean = (DtpExecutor) DtpInterceptorRegistry.plugin(bean, pluginNames, argTypes, args);
if (enhancedBean instanceof EagerDtpExecutor) {
((TaskQueue) enhancedBean.getQueue()).setExecutor((EagerDtpExecutor) enhancedBean);
}
DtpRegistry.registerExecutor(ExecutorWrapper.of(enhancedBean), REGISTER_SOURCE);
return enhancedBean;
}
private Object registerAndReturnCommon(Object bean, String beanName) {
String dtpAnnoValue;
try {
DynamicTp dynamicTp = beanFactory.findAnnotationOnBean(beanName, DynamicTp.class);
if (Objects.nonNull(dynamicTp)) {
dtpAnnoValue = dynamicTp.value();
} else {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (!(beanDefinition instanceof AnnotatedBeanDefinition)) {
return bean;
}
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
MethodMetadata methodMetadata = (MethodMetadata) annotatedBeanDefinition.getSource();
if (Objects.isNull(methodMetadata) || !methodMetadata.isAnnotated(DynamicTp.class.getName())) {
return bean;
}
dtpAnnoValue = Optional.ofNullable(methodMetadata.getAnnotationAttributes(DynamicTp.class.getName()))
.orElse(Collections.emptyMap())
.getOrDefault("value", "")
.toString();
}
} catch (NoSuchBeanDefinitionException e) {
log.warn("There is no bean with the given name {}", beanName, e);
return bean;
}
String poolName = StringUtils.isNotBlank(dtpAnnoValue) ? dtpAnnoValue : beanName;
return doRegisterAndReturnCommon(bean, poolName);
}
private Object doRegisterAndReturnCommon(Object bean, String poolName) {
if (bean instanceof ThreadPoolTaskExecutor) {
ThreadPoolTaskExecutor poolTaskExecutor = (ThreadPoolTaskExecutor) bean;
val proxy = newProxy(poolName, poolTaskExecutor.getThreadPoolExecutor());
try {
ReflectionUtil.setFieldValue("threadPoolExecutor", bean, proxy);
tryWrapTaskDecorator(poolTaskExecutor, proxy);
} catch (IllegalAccessException ignored) { }
DtpRegistry.registerExecutor(new ExecutorWrapper(poolName, proxy), REGISTER_SOURCE);
return bean;
}
Executor proxy;
if (bean instanceof ScheduledThreadPoolExecutor) {
proxy = newScheduledTpProxy(poolName, (ScheduledThreadPoolExecutor) bean);
} else {
proxy = newProxy(poolName, (ThreadPoolExecutor) bean);
}
DtpRegistry.registerExecutor(new ExecutorWrapper(poolName, proxy), REGISTER_SOURCE);
return proxy;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (DefaultListableBeanFactory) beanFactory;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
private ThreadPoolExecutorProxy newProxy(String name, ThreadPoolExecutor originExecutor) {
val proxy = new ThreadPoolExecutorProxy(originExecutor);
shutdownGracefulAsync(originExecutor, name, 0);
return proxy;
}
private ScheduledThreadPoolExecutorProxy newScheduledTpProxy(String name, ScheduledThreadPoolExecutor originExecutor) {
val proxy = new ScheduledThreadPoolExecutorProxy(originExecutor);
shutdownGracefulAsync(originExecutor, name, 0);
return proxy;
}
private void tryWrapTaskDecorator(ThreadPoolTaskExecutor poolTaskExecutor, ThreadPoolExecutorProxy proxy) throws IllegalAccessException {
Object taskDecorator = ReflectionUtil.getFieldValue("taskDecorator", poolTaskExecutor);
if (Objects.isNull(taskDecorator)) {
return;
}
TaskWrapper taskWrapper = (taskDecorator instanceof TaskWrapper) ? (TaskWrapper) taskDecorator : new TaskWrapper() {
@Override
public String name() {
return taskDecorator.getClass().getName();
}
@Override
public Runnable wrap(Runnable runnable) {
return ((TaskDecorator) taskDecorator).decorate(runnable);
}
};
ReflectionUtil.setFieldValue("taskWrappers", proxy, Lists.newArrayList(taskWrapper));
}
}
|
if (!(bean instanceof ThreadPoolExecutor) && !(bean instanceof ThreadPoolTaskExecutor)) {
return bean;
}
if (bean instanceof DtpExecutor) {
return registerAndReturnDtp(bean);
}
// register juc ThreadPoolExecutor or ThreadPoolTaskExecutor
return registerAndReturnCommon(bean, beanName);
| 1,439
| 85
| 1,524
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/spring/YamlPropertySourceFactory.java
|
YamlPropertySourceFactory
|
createPropertySource
|
class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource encodedResource) {<FILL_FUNCTION_BODY>}
}
|
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
if (Objects.isNull(properties)
|| StringUtils.isBlank(encodedResource.getResource().getFilename())) {
return null;
}
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
| 54
| 105
| 159
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/support/BinderHelper.java
|
BinderHelper
|
getBinder
|
class BinderHelper {
private BinderHelper() { }
private static PropertiesBinder getBinder() {<FILL_FUNCTION_BODY>}
public static void bindDtpProperties(Map<?, Object> properties, DtpProperties dtpProperties) {
final PropertiesBinder binder = getBinder();
if (Objects.isNull(binder)) {
return;
}
binder.bindDtpProperties(properties, dtpProperties);
}
public static void bindDtpProperties(Environment environment, DtpProperties dtpProperties) {
final PropertiesBinder binder = getBinder();
if (Objects.isNull(binder)) {
return;
}
binder.bindDtpProperties(environment, dtpProperties);
}
}
|
PropertiesBinder binder = Singleton.INST.get(PropertiesBinder.class);
if (Objects.nonNull(binder)) {
return binder;
}
final PropertiesBinder loadedFirstBinder = ExtensionServiceLoader.getFirst(PropertiesBinder.class);
if (Objects.isNull(loadedFirstBinder)) {
log.error("DynamicTp refresh, no SPI for org.dromara.dynamictp.core.spring.PropertiesBinder.");
return null;
}
Singleton.INST.single(PropertiesBinder.class, loadedFirstBinder);
return loadedFirstBinder;
| 197
| 154
| 351
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/support/DtpBannerPrinter.java
|
DtpBannerPrinter
|
setEnvironment
|
class DtpBannerPrinter implements EnvironmentAware {
private static final String NAME = " :: Dynamic Thread Pool :: ";
private static final String SITE = " :: https://dynamictp.cn ::";
private static final String BANNER = "\n" +
"| __ \\ (_) |__ __| \n" +
"| | | |_ _ _ __ __ _ _ __ ___ _ ___| |_ __ \n" +
"| | | | | | | '_ \\ / _` | '_ ` _ \\| |/ __| | '_ \\ \n" +
"| |__| | |_| | | | | (_| | | | | | | | (__| | |_) |\n" +
"|_____/ \\__, |_| |_|\\__,_|_| |_| |_|_|\\___|_| .__/ \n" +
" __/ | | | \n" +
" |___/ |_| ";
@Override
public void setEnvironment(Environment environment) {<FILL_FUNCTION_BODY>}
}
|
boolean enable = environment.getProperty(DynamicTpConst.BANNER_ENABLED_PROP,
boolean.class, true);
if (enable) {
log.info(BANNER + "\n" + NAME + "\n :: " + VersionUtil.getVersion() + " :: \n" + SITE + "\n");
}
| 286
| 85
| 371
|
<no_super_class>
|
dromara_dynamic-tp
|
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/support/DtpLifecycleSupport.java
|
DtpLifecycleSupport
|
shutdownGracefulAsync
|
class DtpLifecycleSupport {
private DtpLifecycleSupport() { }
/**
* Initialize, do sth.
*
* @param executorWrapper executor wrapper
*/
public static void initialize(ExecutorWrapper executorWrapper) {
executorWrapper.initialize();
}
/**
* Calls {@code internalShutdown} when the BeanFactory destroys
* the task executor instance.
* @param executorWrapper executor wrapper
*/
public static void destroy(ExecutorWrapper executorWrapper) {
if (executorWrapper.isDtpExecutor()) {
destroy((DtpExecutor) executorWrapper.getExecutor());
} else if (executorWrapper.isThreadPoolExecutor()) {
internalShutdown(((ThreadPoolExecutorAdapter) executorWrapper.getExecutor()).getOriginal(),
executorWrapper.getThreadPoolName(),
true,
0);
}
}
public static void destroy(DtpExecutor executor) {
internalShutdown(executor,
executor.getThreadPoolName(),
executor.isWaitForTasksToCompleteOnShutdown(),
executor.getAwaitTerminationSeconds());
}
public static void shutdownGracefulAsync(ExecutorService executor,
String threadPoolName,
int timeout) {<FILL_FUNCTION_BODY>}
/**
* Perform a shutdown on the underlying ExecutorService.
* @param executor the executor to shut down (maybe {@code null})
* @param threadPoolName the name of the thread pool (for logging purposes)
* @param waitForTasksToCompleteOnShutdown whether to wait for tasks to complete on shutdown
* @param awaitTerminationSeconds the maximum number of seconds to wait
*
* @see ExecutorService#shutdown()
* @see ExecutorService#shutdownNow()
*/
public static void internalShutdown(ExecutorService executor,
String threadPoolName,
boolean waitForTasksToCompleteOnShutdown,
int awaitTerminationSeconds) {
if (Objects.isNull(executor)) {
return;
}
log.info("Shutting down ExecutorService, threadPoolName: {}", threadPoolName);
if (waitForTasksToCompleteOnShutdown) {
executor.shutdown();
} else {
for (Runnable remainingTask : executor.shutdownNow()) {
cancelRemainingTask(remainingTask);
}
}
awaitTerminationIfNecessary(executor, threadPoolName, awaitTerminationSeconds);
}
/**
* Cancel the given remaining task which never commended execution,
* as returned from {@link ExecutorService#shutdownNow()}.
* @param task the task to cancel (typically a {@link RunnableFuture})
* @see RunnableFuture#cancel(boolean)
*/
protected static void cancelRemainingTask(Runnable task) {
if (task instanceof Future) {
((Future<?>) task).cancel(true);
}
}
/**
* Wait for the executor to terminate, according to the value of the awaitTerminationSeconds property.
* @param executor executor
*/
private static void awaitTerminationIfNecessary(ExecutorService executor,
String threadPoolName,
int awaitTerminationSeconds) {
if (awaitTerminationSeconds <= 0) {
return;
}
try {
if (!executor.awaitTermination(awaitTerminationSeconds, TimeUnit.SECONDS)) {
log.warn("Timed out while waiting for executor {} to terminate", threadPoolName);
}
} catch (InterruptedException ex) {
log.warn("Interrupted while waiting for executor {} to terminate", threadPoolName);
Thread.currentThread().interrupt();
}
}
}
|
ExecutorService tmpExecutor = Executors.newSingleThreadExecutor();
tmpExecutor.execute(() -> internalShutdown(executor, threadPoolName,
true, timeout));
tmpExecutor.shutdown();
| 966
| 53
| 1,019
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.