How to create a ThreadPoolExecutor that creates threads as needed and expires when applicable?

My use case:

  • Set the minimum size "N" for the thread pool, which implies that the "N" threads are always available after running Executor.
  • Set the maximum size "M" for the thread pool.
  • Incoming tasks must be queued when all M threads are busy.
  • Timed Out (MN) flows based on standby timeout.

I believe that such a setting is possible for the pool manager behind HttpClient. I am trying to achieve this with ThreadPoolExecutor, but cannot find a way. Is it possible?

Here is an example of testing.

public class ExecutorExample {

    public static void main(String[] args) throws InterruptedException {
        int minPoolSize = 2;
        int maxPoolSize = 10;
        int ttlMillis = 100;
        ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize, 
                maxPoolSize, // surprisingly this is not obeyed.
                ttlMillis, 
                TimeUnit.MILLISECONDS, 
                new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
            startupExecutor.execute(new MyRunnable(i));
        }

        for (int i = 0; i < 20; i++) {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
        }
    }

}

class MyRunnable implements Runnable {

    int n;

    public MyRunnable(int n) {
        this.n = n;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + ":" + n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
+4
1

:

        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

ThreadPoolExecutor

EDIT: .

BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(queueCapacity, true);

EDIT2: , . , 2. Se link .

rules-of-a-threadpoolexecutor-pool-size

1, .

new LinkedBlockingQueue<>(1));

3: startupExecutor.getCorePoolSize() startupExecutor.getPoolSize().

0

Source: https://habr.com/ru/post/1675199/


All Articles