diff --git a/common/src/main/java/ctbrec/recorder/ThreadPoolScaler.java b/common/src/main/java/ctbrec/recorder/ThreadPoolScaler.java index 72de156f..2f49c5ee 100644 --- a/common/src/main/java/ctbrec/recorder/ThreadPoolScaler.java +++ b/common/src/main/java/ctbrec/recorder/ThreadPoolScaler.java @@ -15,8 +15,8 @@ public class ThreadPoolScaler { private int[] values = new int[20]; private int index = -1; - private Instant lastAdjustment = Instant.EPOCH; - + private Instant lastAdjustment = Instant.now(); + private Instant downScaleCoolDown = Instant.EPOCH; public ThreadPoolScaler(ThreadPoolExecutor threadPool, int configuredPoolSize) { this.threadPool = threadPool; @@ -25,23 +25,38 @@ public class ThreadPoolScaler { public void tick() { values[getNextIndex()] = threadPool.getActiveCount(); + adjustPoolSize(); + } + + private synchronized void adjustPoolSize() { + Instant now = Instant.now(); + if (Duration.between(lastAdjustment, now).toMillis() > 500) { + double average = calculateAverage(); + int coreSize = threadPool.getCorePoolSize(); + if (average > 0.65 * coreSize) { + threadPool.setCorePoolSize(coreSize + 1); + downScaleCoolDown = now.plusSeconds(30); + LOG.trace("Adjusted scheduler pool size to {}", threadPool.getCorePoolSize()); + } else if (average < 0.15 * coreSize) { + int newValue = Math.max(configuredPoolSize, coreSize - 1); + if (threadPool.getCorePoolSize() != newValue && now.isAfter(downScaleCoolDown)) { + threadPool.setCorePoolSize(newValue); + downScaleCoolDown = now.plusSeconds(10); + LOG.trace("Adjusted scheduler pool size to {}", threadPool.getCorePoolSize()); + } + } + lastAdjustment = now; + LOG.trace("Thread pool size is {}", threadPool.getCorePoolSize()); + } + } + + private double calculateAverage() { int sum = 0; for (int i = 0; i < values.length; i++) { sum += values[i]; } double average = sum / (double) values.length; - - if (Duration.between(lastAdjustment, Instant.now()).toMillis() > 2000) { - int coreSize = threadPool.getCorePoolSize(); - if (average > 0.75 * coreSize) { - threadPool.setCorePoolSize(coreSize + 1); - lastAdjustment = Instant.now(); - } else if (average > 0.25 * coreSize) { - threadPool.setCorePoolSize(Math.max(configuredPoolSize, coreSize - 1)); - lastAdjustment = Instant.now(); - } - LOG.trace("Adjusted scheduler pool size to {}", threadPool.getCorePoolSize()); - } + return average; } private synchronized int getNextIndex() {