Skip to content

Commit

Permalink
misc: 使用ThreadPoolExecutor根据情况动态调整查询线程数量
Browse files Browse the repository at this point in the history
    - 并在闲置10分钟后自动结束线程
    - 同时限制查询线程最多不超过16个
  • Loading branch information
MATRIX-feather committed Oct 14, 2024
1 parent d5d03dc commit 4c02da6
Showing 1 changed file with 28 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,46 @@ public static ExecutorService executor()
if (executor == null || executor.isShutdown())
{
EXECUTOR = executor = createExecutor();

MorphPlugin.getInstance()
.getSLF4JLogger()
.info("Creating new executor with maximum " + getMaximumThreadCount() + " thread(s) for profile lookup.");
}

return executor;
}

private static int getThreadCount()
private static int getMaximumThreadCount()
{
return Math.max(4, Runtime.getRuntime().availableProcessors() / 2);
return Math.min(16, Math.max(4, Runtime.getRuntime().availableProcessors() / 2));
}

private static ExecutorService createExecutor()
{
return Executors.newFixedThreadPool(getThreadCount(), new ThreadFactory()
{
private final AtomicInteger threadCount = new AtomicInteger(0);

@Override
public Thread newThread(@NotNull Runnable runnable)
{
Thread thread = new Thread(runnable);
var threadId = this.threadCount.getAndIncrement();
thread.setName("FeatherMorph Profile Executor #" + threadId);

thread.setUncaughtExceptionHandler((Thread t, Throwable error) ->
return new ThreadPoolExecutor(1, getMaximumThreadCount(),
10, TimeUnit.MINUTES,
new SynchronousQueue<>(),
new ThreadFactory()
{
MorphPlugin.getInstance()
.getSLF4JLogger()
.error("Error occurred in thread " + t.getName(), error);
private final AtomicInteger threadCount = new AtomicInteger(0);

@Override
public Thread newThread(@NotNull Runnable runnable)
{
Thread thread = new Thread(runnable);
var threadId = this.threadCount.getAndIncrement();
thread.setName("FeatherMorph Profile Executor #" + threadId);

thread.setUncaughtExceptionHandler((Thread t, Throwable error) ->
{
MorphPlugin.getInstance()
.getSLF4JLogger()
.error("Error occurred in thread " + t.getName(), error);
});

return thread;
}
});

return thread;
}
});
}

@Nullable
Expand Down

0 comments on commit 4c02da6

Please sign in to comment.