what is the function of ThreadPoolExecutor maximumPoolSize in java

Rafael Lima :

I'm struggling with something stupidly simple...

My real project was suffering of an unknown problem for ages, them i decided to create a very simple test and i got scared with the results...

Here is the test:

ExecutorService t = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(600));
        for (int i = 0; i < 100; i++) {
            final int i1 = i;
            t.execute(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        System.out.println(i1);
                        try {
                            Thread.sleep(5000);
                        }
                        catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            });
        }

I'm creating a thread pool with 10 core thread plus 20 maximumPoolSize then i give to it 100 threads which will simple print a fixed number each...

MY HUMBLE STUPID THOUGHT WAS:

The pool has 10 threads, will print 0-9 randomly then after some instans 10 extra threads will be created and pool will print from 0-19 randomly

This is kind of obvious to me since maxSize is 20 it should accept 20 tasks in worst case...

but the result was 0-9 being printed forever

the question is: What is the point of maximumPoolSize if the extra threads are never scheduled for execution?

Rafael Lima :

As correclty pointed by @Oleg, the pool works fine but there is an implementation detail i wasn't aware.

The extra threads will only be created if the task queue is FULL

this article explains better: http://www.bigsoft.co.uk/blog/2009/11/27/rules-of-a-threadpoolexecutor-pool-size

Take this example. Starting thread pool size is 1, core pool size is 5, max pool size is 10 and the queue is 100.

Sun's way: as requests come in threads will be created up to 5, then tasks will be added to the queue until it reaches 100. When the queue is full new threads will be created up to maxPoolSize. Once all the threads are in use and the queue is full tasks will be rejected. As the queue reduces so does the number of active threads.

User anticipated way: as requests come in threads will be created up to 10, then tasks will be added to the queue until it reaches 100 at which point they are rejected. The number of threads will rename at max until the queue is empty. When the queue is empty the threads will die off until there are corePoolSize left.

So Java waits to last second before your queue blow out to create a new thread...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129610&siteId=1