Supplemental code comments (#904)

pull/906/head
马称 Ma Chen 2 years ago committed by GitHub
parent b883dab4f3
commit 733567e498
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -26,7 +26,6 @@ import java.lang.annotation.Target;
/** /**
* An annotation that enhances the functionality of the jdk acoustic thread pool, * An annotation that enhances the functionality of the jdk acoustic thread pool,
* with the following list of enhancements. * with the following list of enhancements.
*
* <ul> * <ul>
* <li>Dynamic change at runtime</li> * <li>Dynamic change at runtime</li>
* <li>Determine whether an alarm is required at runtime</li> * <li>Determine whether an alarm is required at runtime</li>

@ -45,7 +45,7 @@ import java.util.concurrent.atomic.AtomicLong;
public class DynamicThreadPoolExecutor extends ExtensibleThreadPoolExecutor implements DisposableBean { public class DynamicThreadPoolExecutor extends ExtensibleThreadPoolExecutor implements DisposableBean {
/** /**
* wait for tasks to complete on shutdown * Wait for tasks to complete on shutdown
*/ */
@Getter @Getter
@Setter @Setter
@ -93,14 +93,13 @@ public class DynamicThreadPoolExecutor extends ExtensibleThreadPoolExecutor impl
blockingQueue, threadFactory, rejectedExecutionHandler); blockingQueue, threadFactory, rejectedExecutionHandler);
log.info("Initializing ExecutorService {}", threadPoolId); log.info("Initializing ExecutorService {}", threadPoolId);
this.waitForTasksToCompleteOnShutdown = waitForTasksToCompleteOnShutdown; this.waitForTasksToCompleteOnShutdown = waitForTasksToCompleteOnShutdown;
// init default plugins // Init default plugins.
new DefaultThreadPoolPluginRegistrar(executeTimeOut, awaitTerminationMillis) new DefaultThreadPoolPluginRegistrar(executeTimeOut, awaitTerminationMillis)
.doRegister(this); .doRegister(this);
} }
/** /**
* Invoked by the containing {@code BeanFactory} on destruction of a bean. * Invoked by the containing {@code BeanFactory} on destruction of a bean.
*
*/ */
@Override @Override
public void destroy() { public void destroy() {
@ -238,5 +237,4 @@ public class DynamicThreadPoolExecutor extends ExtensibleThreadPoolExecutor impl
public void setRedundancyHandler(RejectedExecutionHandler handler) { public void setRedundancyHandler(RejectedExecutionHandler handler) {
setRejectedExecutionHandler(handler); setRejectedExecutionHandler(handler);
} }
} }

@ -43,20 +43,19 @@ import java.util.concurrent.*;
public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements ThreadPoolPluginSupport { public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements ThreadPoolPluginSupport {
/** /**
* thread pool id * Thread pool id
*/ */
@Getter @Getter
@NonNull
private final String threadPoolId; private final String threadPoolId;
/** /**
* action aware registry * Action aware registry
*/ */
@Getter @Getter
private final ThreadPoolPluginManager threadPoolPluginManager; private final ThreadPoolPluginManager threadPoolPluginManager;
/** /**
* handler wrapper, any changes to the current instance {@link RejectedExecutionHandler} should be made through this wrapper * Handler wrapper, any changes to the current instance {@link RejectedExecutionHandler} should be made through this wrapper
*/ */
private final RejectedAwareHandlerWrapper handlerWrapper; private final RejectedAwareHandlerWrapper handlerWrapper;
@ -97,12 +96,10 @@ public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements
@NonNull ThreadFactory threadFactory, @NonNull ThreadFactory threadFactory,
@NonNull RejectedExecutionHandler handler) { @NonNull RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
// Pool extended info.
// pool extended info
this.threadPoolId = threadPoolId; this.threadPoolId = threadPoolId;
this.threadPoolPluginManager = threadPoolPluginManager; this.threadPoolPluginManager = threadPoolPluginManager;
// Proxy handler to support Aware callback.
// proxy handler to support Aware callback
while (handler instanceof RejectedAwareHandlerWrapper) { while (handler instanceof RejectedAwareHandlerWrapper) {
handler = ((RejectedAwareHandlerWrapper) handler).getHandler(); handler = ((RejectedAwareHandlerWrapper) handler).getHandler();
} }
@ -191,7 +188,7 @@ public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements
} }
/** /**
* {@inheritDoc}. * {@inheritDoc}
* *
* <p><b>Before calling the superclass method, {@link ShutdownAwarePlugin#afterTerminated} will be called first. * <p><b>Before calling the superclass method, {@link ShutdownAwarePlugin#afterTerminated} will be called first.
*/ */
@ -291,20 +288,19 @@ public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements
private static class RejectedAwareHandlerWrapper implements RejectedExecutionHandler { private static class RejectedAwareHandlerWrapper implements RejectedExecutionHandler {
/** /**
* thread-pool action aware registry * Thread-pool action aware registry
*/ */
private final ThreadPoolPluginManager registry; private final ThreadPoolPluginManager registry;
/** /**
* original target * Original target
*/ */
@NonNull
@Setter @Setter
@Getter @Getter
private RejectedExecutionHandler handler; private RejectedExecutionHandler handler;
/** /**
* Call {@link RejectedAwarePlugin#beforeRejectedExecution}, then reject the task * Call {@link RejectedAwarePlugin#beforeRejectedExecution}, then reject the task.
* *
* @param r the runnable task requested to be executed * @param r the runnable task requested to be executed
* @param executor the executor attempting to execute this task * @param executor the executor attempting to execute this task
@ -315,6 +311,5 @@ public class ExtensibleThreadPoolExecutor extends ThreadPoolExecutor implements
rejectedAwarePluginList.forEach(aware -> aware.beforeRejectedExecution(r, executor)); rejectedAwarePluginList.forEach(aware -> aware.beforeRejectedExecution(r, executor));
handler.rejectedExecution(r, executor); handler.rejectedExecution(r, executor);
} }
} }
} }

@ -29,7 +29,6 @@ import cn.hippo4j.message.request.AlarmNotifyRequest;
import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest;
import cn.hippo4j.message.service.Hippo4jSendMessageService; import cn.hippo4j.message.service.Hippo4jSendMessageService;
import cn.hippo4j.message.service.ThreadPoolNotifyAlarm; import cn.hippo4j.message.service.ThreadPoolNotifyAlarm;
import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -37,7 +36,14 @@ import org.springframework.boot.CommandLineRunner;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.*; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/** /**
* Thread-pool notify alarm handler. * Thread-pool notify alarm handler.
@ -46,7 +52,6 @@ import java.util.concurrent.*;
@RequiredArgsConstructor @RequiredArgsConstructor
public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner { public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner {
@NonNull
private final Hippo4jSendMessageService hippo4jSendMessageService; private final Hippo4jSendMessageService hippo4jSendMessageService;
@Value("${spring.profiles.active:UNKNOWN}") @Value("${spring.profiles.active:UNKNOWN}")
@ -96,8 +101,8 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Check thread pool capacity alarm. * Check thread pool capacity alarm.
* *
* @param threadPoolId * @param threadPoolId thread-pool id
* @param threadPoolExecutor * @param threadPoolExecutor thread-pool executor
*/ */
public void checkPoolCapacityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) { public void checkPoolCapacityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId); ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId);
@ -119,8 +124,8 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Check thread pool activity alarm. * Check thread pool activity alarm.
* *
* @param threadPoolId * @param threadPoolId thread-pool id
* @param threadPoolExecutor * @param threadPoolExecutor thread-pool executor
*/ */
public void checkPoolActivityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) { public void checkPoolActivityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId); ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId);
@ -141,7 +146,7 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Async send rejected alarm. * Async send rejected alarm.
* *
* @param threadPoolId * @param threadPoolId thread-pool id
*/ */
public void asyncSendRejectedAlarm(String threadPoolId) { public void asyncSendRejectedAlarm(String threadPoolId) {
Runnable checkPoolRejectedAlarmTask = () -> { Runnable checkPoolRejectedAlarmTask = () -> {
@ -162,10 +167,10 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Async send execute time out alarm. * Async send execute time out alarm.
* *
* @param threadPoolId * @param threadPoolId thread-pool id
* @param executeTime * @param executeTime execute time
* @param executeTimeOut * @param executeTimeOut execute time-out
* @param threadPoolExecutor * @param threadPoolExecutor thread-pool executor
*/ */
public void asyncSendExecuteTimeOutAlarm(String threadPoolId, long executeTime, long executeTimeOut, ThreadPoolExecutor threadPoolExecutor) { public void asyncSendExecuteTimeOutAlarm(String threadPoolId, long executeTime, long executeTimeOut, ThreadPoolExecutor threadPoolExecutor) {
ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId); ThreadPoolNotifyAlarm alarmConfig = GlobalNotifyAlarmManage.get(threadPoolId);
@ -193,7 +198,7 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Send pool config change. * Send pool config change.
* *
* @param request * @param request change parameter notify request
*/ */
public void sendPoolConfigChange(ChangeParameterNotifyRequest request) { public void sendPoolConfigChange(ChangeParameterNotifyRequest request) {
request.setActive(active.toUpperCase()); request.setActive(active.toUpperCase());
@ -206,7 +211,7 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
/** /**
* Build alarm notify request. * Build alarm notify request.
* *
* @param threadPoolExecutor * @param threadPoolExecutor thread-pool executor
* @return * @return
*/ */
public AlarmNotifyRequest buildAlarmNotifyRequest(ThreadPoolExecutor threadPoolExecutor) { public AlarmNotifyRequest buildAlarmNotifyRequest(ThreadPoolExecutor threadPoolExecutor) {

@ -47,6 +47,9 @@ public class DynamicThreadPoolBannerHandler implements InitializingBean {
printBanner(); printBanner();
} }
/**
* Print banner.
*/
private void printBanner() { private void printBanner() {
String banner = " __ __ ___ ___ __ \n" + String banner = " __ __ ___ ___ __ \n" +
" | |--.|__|.-----..-----..-----.| | | |__|\n" + " | |--.|__|.-----..-----..-----.| | | |__|\n" +
@ -67,6 +70,11 @@ public class DynamicThreadPoolBannerHandler implements InitializingBean {
} }
} }
/**
* Get version.
*
* @return hippo4j version
*/
public static String getVersion() { public static String getVersion() {
final Package pkg = DynamicThreadPoolBannerHandler.class.getPackage(); final Package pkg = DynamicThreadPoolBannerHandler.class.getPackage();
return pkg != null ? pkg.getImplementationVersion() : ""; return pkg != null ? pkg.getImplementationVersion() : "";

@ -32,7 +32,6 @@ public interface ExecuteAwarePlugin extends ThreadPoolPlugin {
* @see ExtensibleThreadPoolExecutor#beforeExecute * @see ExtensibleThreadPoolExecutor#beforeExecute
*/ */
default void beforeExecute(Thread thread, Runnable runnable) { default void beforeExecute(Thread thread, Runnable runnable) {
// do noting
} }
/** /**
@ -43,7 +42,5 @@ public interface ExecuteAwarePlugin extends ThreadPoolPlugin {
* @see ExtensibleThreadPoolExecutor#afterExecute * @see ExtensibleThreadPoolExecutor#afterExecute
*/ */
default void afterExecute(Runnable runnable, Throwable throwable) { default void afterExecute(Runnable runnable, Throwable throwable) {
// do nothing
} }
} }

@ -31,12 +31,12 @@ import java.util.List;
public class PluginRuntime { public class PluginRuntime {
/** /**
* plugin id * Plugin id
*/ */
private final String pluginId; private final String pluginId;
/** /**
* runtime info * Runtime info
*/ */
private final List<Info> infoList = new ArrayList<>(); private final List<Info> infoList = new ArrayList<>();
@ -52,12 +52,21 @@ public class PluginRuntime {
return this; return this;
} }
/**
* Plugin runtime info.
*/
@Getter @Getter
@RequiredArgsConstructor @RequiredArgsConstructor
public static class Info { public static class Info {
/**
* Name
*/
private final String name; private final String name;
/**
* Value
*/
private final Object value; private final Object value;
} }
} }

@ -31,7 +31,5 @@ public interface RejectedAwarePlugin extends ThreadPoolPlugin {
* @param executor executor * @param executor executor
*/ */
default void beforeRejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { default void beforeRejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
// do nothing
} }
} }

@ -35,7 +35,6 @@ public interface ShutdownAwarePlugin extends ThreadPoolPlugin {
* @see ThreadPoolExecutor#shutdownNow() * @see ThreadPoolExecutor#shutdownNow()
*/ */
default void beforeShutdown(ThreadPoolExecutor executor) { default void beforeShutdown(ThreadPoolExecutor executor) {
// do nothing
} }
/** /**
@ -47,7 +46,6 @@ public interface ShutdownAwarePlugin extends ThreadPoolPlugin {
* @see ThreadPoolExecutor#shutdownNow() * @see ThreadPoolExecutor#shutdownNow()
*/ */
default void afterShutdown(ThreadPoolExecutor executor, List<Runnable> remainingTasks) { default void afterShutdown(ThreadPoolExecutor executor, List<Runnable> remainingTasks) {
// do nothing
} }
/** /**
@ -57,7 +55,5 @@ public interface ShutdownAwarePlugin extends ThreadPoolPlugin {
* @see ThreadPoolExecutor#terminated() * @see ThreadPoolExecutor#terminated()
*/ */
default void afterTerminated(ExtensibleThreadPoolExecutor executor) { default void afterTerminated(ExtensibleThreadPoolExecutor executor) {
// do nothing
} }
} }

@ -61,5 +61,4 @@ public interface TaskAwarePlugin extends ThreadPoolPlugin {
default Runnable beforeTaskExecute(Runnable runnable) { default Runnable beforeTaskExecute(Runnable runnable) {
return runnable; return runnable;
} }
} }

@ -57,7 +57,6 @@ public interface ThreadPoolPlugin {
* @see ThreadPoolPluginManager#register * @see ThreadPoolPluginManager#register
*/ */
default void start() { default void start() {
// do nothing
} }
/** /**
@ -67,7 +66,6 @@ public interface ThreadPoolPlugin {
* @see ThreadPoolPluginManager#clear * @see ThreadPoolPluginManager#clear
*/ */
default void stop() { default void stop() {
// do nothing
} }
/** /**
@ -78,5 +76,4 @@ public interface ThreadPoolPlugin {
default PluginRuntime getPluginRuntime() { default PluginRuntime getPluginRuntime() {
return new PluginRuntime(getId()); return new PluginRuntime(getId());
} }
} }

@ -36,7 +36,7 @@ import java.util.Optional;
public abstract class AbstractTaskTimerPlugin implements ExecuteAwarePlugin { public abstract class AbstractTaskTimerPlugin implements ExecuteAwarePlugin {
/** /**
* start times of executed tasks * Start times of executed tasks
*/ */
private final ThreadLocal<Long> startTimes = new ThreadLocal<>(); private final ThreadLocal<Long> startTimes = new ThreadLocal<>();
@ -84,5 +84,4 @@ public abstract class AbstractTaskTimerPlugin implements ExecuteAwarePlugin {
* @param taskExecuteTime execute time of task * @param taskExecuteTime execute time of task
*/ */
protected abstract void processTaskTime(long taskExecuteTime); protected abstract void processTaskTime(long taskExecuteTime);
} }

@ -45,7 +45,7 @@ public class TaskDecoratorPlugin implements TaskAwarePlugin {
} }
/** /**
* decorators * Decorators
*/ */
@Getter @Getter
private final List<TaskDecorator> decorators = new ArrayList<>(); private final List<TaskDecorator> decorators = new ArrayList<>();
@ -77,7 +77,7 @@ public class TaskDecoratorPlugin implements TaskAwarePlugin {
} }
/** /**
* Add a decorator * Add a decorator.
* *
* @param decorator decorator * @param decorator decorator
*/ */
@ -87,19 +87,16 @@ public class TaskDecoratorPlugin implements TaskAwarePlugin {
} }
/** /**
* Clear all decorators * Clear all decorators.
*
*/ */
public void clearDecorators() { public void clearDecorators() {
decorators.clear(); decorators.clear();
} }
/** /**
* Remove decorators * Remove decorators.
*
*/ */
public void removeDecorator(TaskDecorator decorator) { public void removeDecorator(TaskDecorator decorator) {
decorators.remove(decorator); decorators.remove(decorator);
} }
} }

@ -43,7 +43,7 @@ public class TaskRejectCountRecordPlugin implements RejectedAwarePlugin {
} }
/** /**
* rejection count * Rejection count
*/ */
@Setter @Setter
@Getter @Getter
@ -72,12 +72,11 @@ public class TaskRejectCountRecordPlugin implements RejectedAwarePlugin {
} }
/** /**
* Get reject count num * Get reject count num.
* *
* @return reject count num * @return reject count num
*/ */
public Long getRejectCountNum() { public Long getRejectCountNum() {
return rejectCount.get(); return rejectCount.get();
} }
} }

@ -34,27 +34,27 @@ public class TaskTimeRecordPlugin extends AbstractTaskTimerPlugin {
public static final String PLUGIN_NAME = "task-time-record-plugin"; public static final String PLUGIN_NAME = "task-time-record-plugin";
/** /**
* Lock instance. * Lock instance
*/ */
private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final ReadWriteLock lock = new ReentrantReadWriteLock();
/** /**
* Total execution milli time of all tasks. * Total execution milli time of all tasks
*/ */
private long totalTaskTimeMillis = 0L; private long totalTaskTimeMillis = 0L;
/** /**
* Maximum task milli execution time, default -1. * Maximum task milli execution time, default -1
*/ */
private long maxTaskTimeMillis = -1L; private long maxTaskTimeMillis = -1L;
/** /**
* Minimal task milli execution time, default -1. * Minimal task milli execution time, default -1
*/ */
private long minTaskTimeMillis = -1L; private long minTaskTimeMillis = -1L;
/** /**
* Count of completed task. * Count of completed task
*/ */
private long taskCount = 0L; private long taskCount = 0L;
@ -137,27 +137,27 @@ public class TaskTimeRecordPlugin extends AbstractTaskTimerPlugin {
public static class Summary { public static class Summary {
/** /**
* Total execution nano time of all tasks. * Total execution nano time of all tasks
*/ */
private final long totalTaskTimeMillis; private final long totalTaskTimeMillis;
/** /**
* Maximum task nano execution time. * Maximum task nano execution time
*/ */
private final long maxTaskTimeMillis; private final long maxTaskTimeMillis;
/** /**
* Minimal task nano execution time. * Minimal task nano execution time
*/ */
private final long minTaskTimeMillis; private final long minTaskTimeMillis;
/** /**
* Count of completed task. * Count of completed task
*/ */
private final long taskCount; private final long taskCount;
/** /**
* Get the avg task time in milliseconds. * Get the avg task time in milliseconds
* *
* @return avg task time * @return avg task time
*/ */
@ -165,7 +165,5 @@ public class TaskTimeRecordPlugin extends AbstractTaskTimerPlugin {
long totalTaskCount = getTaskCount(); long totalTaskCount = getTaskCount();
return totalTaskCount > 0L ? getTotalTaskTimeMillis() / totalTaskCount : -1; return totalTaskCount > 0L ? getTotalTaskTimeMillis() / totalTaskCount : -1;
} }
} }
} }

@ -35,16 +35,19 @@ public class TaskTimeoutNotifyAlarmPlugin extends AbstractTaskTimerPlugin {
public static final String PLUGIN_NAME = "task-timeout-notify-alarm-plugin"; public static final String PLUGIN_NAME = "task-timeout-notify-alarm-plugin";
/** /**
* threadPoolId * Thread-pool id
*/ */
private final String threadPoolId; private final String threadPoolId;
/**
* Execute time-out
*/
@Getter @Getter
@Setter @Setter
private Long executeTimeOut; private Long executeTimeOut;
/** /**
* thread-pool * Thread-pool executor
*/ */
private final ThreadPoolExecutor threadPoolExecutor; private final ThreadPoolExecutor threadPoolExecutor;
@ -74,5 +77,4 @@ public class TaskTimeoutNotifyAlarmPlugin extends AbstractTaskTimerPlugin {
.ifPresent(handler -> handler.asyncSendExecuteTimeOutAlarm( .ifPresent(handler -> handler.asyncSendExecuteTimeOutAlarm(
threadPoolId, taskExecuteTime, executeTimeOut, threadPoolExecutor)); threadPoolId, taskExecuteTime, executeTimeOut, threadPoolExecutor));
} }
} }

@ -54,7 +54,7 @@ public class ThreadPoolExecutorShutdownPlugin implements ShutdownAwarePlugin {
} }
/** /**
* await termination millis * Await termination millis
*/ */
@Setter @Setter
public long awaitTerminationMillis; public long awaitTerminationMillis;
@ -141,5 +141,4 @@ public class ThreadPoolExecutorShutdownPlugin implements ShutdownAwarePlugin {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
} }

@ -52,32 +52,32 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager { public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager {
/** /**
* lock of this instance * Lock of this instance
*/ */
private final ReadWriteLock instanceLock = new ReentrantReadWriteLock(); private final ReadWriteLock instanceLock = new ReentrantReadWriteLock();
/** /**
* Registered {@link ThreadPoolPlugin}. * Registered {@link ThreadPoolPlugin}
*/ */
private final Map<String, ThreadPoolPlugin> registeredPlugins = new ConcurrentHashMap<>(16); private final Map<String, ThreadPoolPlugin> registeredPlugins = new ConcurrentHashMap<>(16);
/** /**
* Registered {@link TaskAwarePlugin}. * Registered {@link TaskAwarePlugin}
*/ */
private final List<TaskAwarePlugin> taskAwarePluginList = new CopyOnWriteArrayList<>(); private final List<TaskAwarePlugin> taskAwarePluginList = new CopyOnWriteArrayList<>();
/** /**
* Registered {@link ExecuteAwarePlugin}. * Registered {@link ExecuteAwarePlugin}
*/ */
private final List<ExecuteAwarePlugin> executeAwarePluginList = new CopyOnWriteArrayList<>(); private final List<ExecuteAwarePlugin> executeAwarePluginList = new CopyOnWriteArrayList<>();
/** /**
* Registered {@link RejectedAwarePlugin}. * Registered {@link RejectedAwarePlugin}
*/ */
private final List<RejectedAwarePlugin> rejectedAwarePluginList = new CopyOnWriteArrayList<>(); private final List<RejectedAwarePlugin> rejectedAwarePluginList = new CopyOnWriteArrayList<>();
/** /**
* Registered {@link ShutdownAwarePlugin}. * Registered {@link ShutdownAwarePlugin}
*/ */
private final List<ShutdownAwarePlugin> shutdownAwarePluginList = new CopyOnWriteArrayList<>(); private final List<ShutdownAwarePlugin> shutdownAwarePluginList = new CopyOnWriteArrayList<>();
@ -115,10 +115,7 @@ public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager {
try { try {
String id = plugin.getId(); String id = plugin.getId();
Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered"); Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered");
// register plugin
registeredPlugins.put(id, plugin); registeredPlugins.put(id, plugin);
// quick index
if (plugin instanceof TaskAwarePlugin) { if (plugin instanceof TaskAwarePlugin) {
taskAwarePluginList.add((TaskAwarePlugin) plugin); taskAwarePluginList.add((TaskAwarePlugin) plugin);
} }
@ -171,7 +168,6 @@ public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager {
Optional.ofNullable(pluginId) Optional.ofNullable(pluginId)
.map(registeredPlugins::remove) .map(registeredPlugins::remove)
.ifPresent(plugin -> { .ifPresent(plugin -> {
// remove quick index if necessary
if (plugin instanceof TaskAwarePlugin) { if (plugin instanceof TaskAwarePlugin) {
taskAwarePluginList.remove(plugin); taskAwarePluginList.remove(plugin);
} }
@ -227,7 +223,7 @@ public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager {
} }
/** /**
* Get {@link ThreadPoolPlugin} * Get {@link ThreadPoolPlugin}.
* *
* @param pluginId plugin id * @param pluginId plugin id
* @param <A> plugin type * @param <A> plugin type
@ -314,5 +310,4 @@ public class DefaultThreadPoolPluginManager implements ThreadPoolPluginManager {
readLock.unlock(); readLock.unlock();
} }
} }
} }

@ -38,12 +38,12 @@ public class DefaultThreadPoolPluginRegistrar implements ThreadPoolPluginRegistr
public static final String REGISTRAR_NAME = "DefaultThreadPoolPluginRegistrar"; public static final String REGISTRAR_NAME = "DefaultThreadPoolPluginRegistrar";
/** /**
* execute time out * Execute time out
*/ */
private long executeTimeOut; private long executeTimeOut;
/** /**
* await termination millis * Await termination millis
*/ */
private long awaitTerminationMillis; private long awaitTerminationMillis;
@ -64,14 +64,10 @@ public class DefaultThreadPoolPluginRegistrar implements ThreadPoolPluginRegistr
*/ */
@Override @Override
public void doRegister(ThreadPoolPluginSupport support) { public void doRegister(ThreadPoolPluginSupport support) {
// callback when task execute
support.register(new TaskDecoratorPlugin()); support.register(new TaskDecoratorPlugin());
support.register(new TaskTimeoutNotifyAlarmPlugin(support.getThreadPoolId(), executeTimeOut, support.getThreadPoolExecutor())); support.register(new TaskTimeoutNotifyAlarmPlugin(support.getThreadPoolId(), executeTimeOut, support.getThreadPoolExecutor()));
// callback when task rejected
support.register(new TaskRejectCountRecordPlugin()); support.register(new TaskRejectCountRecordPlugin());
support.register(new TaskRejectNotifyAlarmPlugin()); support.register(new TaskRejectNotifyAlarmPlugin());
// callback when pool shutdown
support.register(new ThreadPoolExecutorShutdownPlugin(awaitTerminationMillis)); support.register(new ThreadPoolExecutorShutdownPlugin(awaitTerminationMillis));
} }
} }

@ -32,7 +32,7 @@ import java.util.Optional;
public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager { public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager {
/** /**
* default instance * Default instance
*/ */
public static final EmptyThreadPoolPluginManager INSTANCE = new EmptyThreadPoolPluginManager(); public static final EmptyThreadPoolPluginManager INSTANCE = new EmptyThreadPoolPluginManager();
@ -41,7 +41,6 @@ public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager {
*/ */
@Override @Override
public void clear() { public void clear() {
// do nothing
} }
/** /**
@ -64,7 +63,6 @@ public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager {
*/ */
@Override @Override
public void register(ThreadPoolPlugin plugin) { public void register(ThreadPoolPlugin plugin) {
// do nothing
} }
/** /**
@ -90,17 +88,16 @@ public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager {
} }
/** /**
* Unregister {@link ThreadPoolPlugin} * Unregister {@link ThreadPoolPlugin}.
* *
* @param pluginId plugin id * @param pluginId plugin id
*/ */
@Override @Override
public void unregister(String pluginId) { public void unregister(String pluginId) {
// do nothing
} }
/** /**
* Get {@link ThreadPoolPlugin} * Get {@link ThreadPoolPlugin}.
* *
* @param pluginId plugin id * @param pluginId plugin id
* @return {@link ThreadPoolPlugin} * @return {@link ThreadPoolPlugin}
@ -150,5 +147,4 @@ public class EmptyThreadPoolPluginManager implements ThreadPoolPluginManager {
public Collection<TaskAwarePlugin> getTaskAwarePluginList() { public Collection<TaskAwarePlugin> getTaskAwarePluginList() {
return Collections.emptyList(); return Collections.emptyList();
} }
} }

@ -54,7 +54,7 @@ public interface ThreadPoolPluginManager {
Collection<ThreadPoolPlugin> getAllPlugins(); Collection<ThreadPoolPlugin> getAllPlugins();
/** /**
* Register a {@link ThreadPoolPlugin} * Register a {@link ThreadPoolPlugin}.
* *
* @param plugin plugin * @param plugin plugin
* @throws IllegalArgumentException thrown when a plugin with the same {@link ThreadPoolPlugin#getId()} * @throws IllegalArgumentException thrown when a plugin with the same {@link ThreadPoolPlugin#getId()}
@ -80,14 +80,14 @@ public interface ThreadPoolPluginManager {
boolean isRegistered(String pluginId); boolean isRegistered(String pluginId);
/** /**
* Unregister {@link ThreadPoolPlugin} * Unregister {@link ThreadPoolPlugin}.
* *
* @param pluginId plugin id * @param pluginId plugin id
*/ */
void unregister(String pluginId); void unregister(String pluginId);
/** /**
* Get {@link ThreadPoolPlugin} * Get {@link ThreadPoolPlugin}.
* *
* @param pluginId plugin id * @param pluginId plugin id
* @param <A> target aware type * @param <A> target aware type
@ -172,5 +172,4 @@ public interface ThreadPoolPluginManager {
return getPlugin(pluginId) return getPlugin(pluginId)
.map(ThreadPoolPlugin::getPluginRuntime); .map(ThreadPoolPlugin::getPluginRuntime);
} }
} }

@ -38,5 +38,4 @@ public interface ThreadPoolPluginRegistrar {
* @param support thread pool plugin manager delegate * @param support thread pool plugin manager delegate
*/ */
void doRegister(ThreadPoolPluginSupport support); void doRegister(ThreadPoolPluginSupport support);
} }

@ -94,7 +94,7 @@ public interface ThreadPoolPluginSupport extends ThreadPoolPluginManager {
} }
/** /**
* Unregister {@link ThreadPoolPlugin} * Unregister {@link ThreadPoolPlugin}.
* *
* @param pluginId name * @param pluginId name
*/ */
@ -114,7 +114,7 @@ public interface ThreadPoolPluginSupport extends ThreadPoolPluginManager {
} }
/** /**
* Get {@link ThreadPoolPlugin} * Get {@link ThreadPoolPlugin}.
* *
* @param pluginId target name * @param pluginId target name
* @return {@link ThreadPoolPlugin}, null if unregister * @return {@link ThreadPoolPlugin}, null if unregister
@ -164,5 +164,4 @@ public interface ThreadPoolPluginSupport extends ThreadPoolPluginManager {
default Collection<TaskAwarePlugin> getTaskAwarePluginList() { default Collection<TaskAwarePlugin> getTaskAwarePluginList() {
return getThreadPoolPluginManager().getTaskAwarePluginList(); return getThreadPoolPluginManager().getTaskAwarePluginList();
} }
} }

@ -34,10 +34,19 @@ import java.util.concurrent.atomic.AtomicLong;
@AllArgsConstructor @AllArgsConstructor
public class RejectedProxyInvocationHandler implements InvocationHandler { public class RejectedProxyInvocationHandler implements InvocationHandler {
/**
* Target object
*/
private final Object target; private final Object target;
/**
* Thread-pool id
*/
private final String threadPoolId; private final String threadPoolId;
/**
* Reject count
*/
private final AtomicLong rejectCount; private final AtomicLong rejectCount;
@Override @Override

@ -33,9 +33,9 @@ public class RejectedProxyUtil {
/** /**
* Proxy rejected execution. * Proxy rejected execution.
* *
* @param rejectedExecutionHandler * @param rejectedExecutionHandler rejected execution handler
* @param threadPoolId * @param threadPoolId thread-pool id
* @param rejectedNum * @param rejectedNum rejected num
* @return * @return
*/ */
public static RejectedExecutionHandler createProxy(RejectedExecutionHandler rejectedExecutionHandler, String threadPoolId, AtomicLong rejectedNum) { public static RejectedExecutionHandler createProxy(RejectedExecutionHandler rejectedExecutionHandler, String threadPoolId, AtomicLong rejectedNum) {

@ -34,7 +34,7 @@ public class ExecutorTraceContextUtil {
/** /**
* Get and remove. * Get and remove.
* *
* @return * @return timeout trace
*/ */
public static String getAndRemoveTimeoutTrace() { public static String getAndRemoveTimeoutTrace() {
String val = MDC.get(EXECUTE_TIMEOUT_TRACE_KEY); String val = MDC.get(EXECUTE_TIMEOUT_TRACE_KEY);
@ -45,7 +45,7 @@ public class ExecutorTraceContextUtil {
/** /**
* Put execute timeout trace. * Put execute timeout trace.
* *
* @param trace * @param trace trace
*/ */
public static void putExecuteTimeoutTrace(String trace) { public static void putExecuteTimeoutTrace(String trace) {
MDC.put(EXECUTE_TIMEOUT_TRACE, trace); MDC.put(EXECUTE_TIMEOUT_TRACE, trace);
@ -54,7 +54,7 @@ public class ExecutorTraceContextUtil {
/** /**
* Set execute timeout trace key. * Set execute timeout trace key.
* *
* @param key * @param key trace key
*/ */
public static void setExecuteTimeoutTraceKey(String key) { public static void setExecuteTimeoutTraceKey(String key) {
EXECUTE_TIMEOUT_TRACE_KEY = key; EXECUTE_TIMEOUT_TRACE_KEY = key;

@ -38,14 +38,20 @@ import static cn.hippo4j.common.constant.Constants.IDENTIFY_SLICER_SYMBOL;
*/ */
public class IdentifyUtil { public class IdentifyUtil {
private static String IDENTIFY;
public static final String CLIENT_IDENTIFICATION_VALUE = IdUtil.simpleUUID();
static { static {
DynamicThreadPoolServiceLoader.register(ClientNetworkService.class); DynamicThreadPoolServiceLoader.register(ClientNetworkService.class);
} }
/**
* Identify
*/
private static String IDENTIFY;
/**
* Client identification value
*/
public static final String CLIENT_IDENTIFICATION_VALUE = IdUtil.simpleUUID();
/** /**
* Generate identify. * Generate identify.
* *

@ -27,14 +27,29 @@ import java.util.concurrent.atomic.AtomicLong;
*/ */
public class SystemClock { public class SystemClock {
/**
* Period
*/
private final int period; private final int period;
/**
* Now
*/
private final AtomicLong now; private final AtomicLong now;
/**
* Thread name
*/
private static final String THREAD_NAME = "system.clock"; private static final String THREAD_NAME = "system.clock";
/**
* Instance holder.
*/
private static class InstanceHolder { private static class InstanceHolder {
/**
* System clock instance
*/
private static final SystemClock INSTANCE = new SystemClock(1); private static final SystemClock INSTANCE = new SystemClock(1);
} }
@ -44,10 +59,18 @@ public class SystemClock {
scheduleClockUpdating(); scheduleClockUpdating();
} }
/**
* Instance.
*
* @return System clock instance
*/
private static SystemClock instance() { private static SystemClock instance() {
return InstanceHolder.INSTANCE; return InstanceHolder.INSTANCE;
} }
/**
* Schedule clock updating.
*/
private void scheduleClockUpdating() { private void scheduleClockUpdating() {
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, runnable -> { ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, runnable -> {
Thread thread = new Thread(runnable, THREAD_NAME); Thread thread = new Thread(runnable, THREAD_NAME);
@ -57,10 +80,20 @@ public class SystemClock {
scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS); scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
} }
/**
* Current time millis.
*
* @return current time millis
*/
private long currentTimeMillis() { private long currentTimeMillis() {
return now.get(); return now.get();
} }
/**
* Now.
*
* @return current time millis
*/
public static long now() { public static long now() {
return instance().currentTimeMillis(); return instance().currentTimeMillis();
} }

@ -84,7 +84,6 @@ public class InetUtils implements Closeable {
} else { } else {
continue; continue;
} }
// @formatter:off
if (!ignoreInterface(ifc.getDisplayName())) { if (!ignoreInterface(ifc.getDisplayName())) {
for (Enumeration<InetAddress> addrs = ifc for (Enumeration<InetAddress> addrs = ifc
.getInetAddresses(); addrs.hasMoreElements(); ) { .getInetAddresses(); addrs.hasMoreElements(); ) {
@ -98,7 +97,6 @@ public class InetUtils implements Closeable {
} }
} }
} }
// @formatter:on
} }
} }
} catch (IOException ex) { } catch (IOException ex) {
@ -150,7 +148,6 @@ public class InetUtils implements Closeable {
public HostInfo convertAddress(final InetAddress address) { public HostInfo convertAddress(final InetAddress address) {
HostInfo hostInfo = new HostInfo(); HostInfo hostInfo = new HostInfo();
Future<String> result = this.executorService.submit(address::getHostName); Future<String> result = this.executorService.submit(address::getHostName);
String hostname; String hostname;
try { try {
hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS); hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS);

Loading…
Cancel
Save