0

I have recently used ScheduledExecutorService and I am using the Executors.newScheduledThreadPool() method. I am confused at the way it is working. I have created a program which executes every 5 sec delay and print a statement. But as per the API is concerned the Executors.newScheduledThreadPool() is used to create threads. So in my example I am using below code

public class TestExecuterService {

    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(0);
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("Print every interval");
            }
        }, 0, 5, TimeUnit.SECONDS);  // execute every x seconds

    }

}

Here I have used ScheduledExecutorService ses = Executors.newScheduledThreadPool(0); So I am assigning 0 to the thread pool. But the program is functioning the same when I assign 10 to the thread pool i.e Executors.newScheduledThreadPool(10);. So what is the function of the Executors.newScheduledThreadPool() method? Please execuse me if this question is silly.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Mandrek
  • 1,159
  • 6
  • 25
  • 55
  • did you read the documentation for `newScheduledThreadPool`, especially the part relative to the argument? – njzk2 Oct 04 '17 at 03:47
  • @RC. nope "if corePoolSize **<** 0" – njzk2 Oct 04 '17 at 03:47
  • my bad I was reading the wrong one :p –  Oct 04 '17 at 03:49
  • correct doc link: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newScheduledThreadPool-int- –  Oct 04 '17 at 03:50
  • 1
    What difference in behavior would you expect to see? In both cases, it’s creating a thread to service your recurring action. The only difference is when you pass `10`, the pool will keep at least 10 worker threads allocated at all times, even though they are not needed. In either case, it will spawn more threads if they are needed. The `corePoolSize` argument is the _minimum_ number of threads to keep in the pool. – Mike Strobel Oct 04 '17 at 03:56
  • @MikeStrobel thanks for the explanation , but then how 0 is working ? If i assign 0 that means no thread is created in the pool wright? then how it works – Mandrek Oct 04 '17 at 04:42
  • It means the pool starts out empty and may be kept empty when idle. The pool is not _limited_ to that size, though; more threads will be created as needed when the pool is empty or all workers are busy. – Mike Strobel Oct 04 '17 at 11:01
  • 1
    @MikeStrobel `corePoolSize` is actually the **max** possible size of the thread-pool -> https://stackoverflow.com/a/39040374/1925388 – Anmol Singh Jaggi May 29 '20 at 11:53
  • And setting it to 0 will still cause 1 thread to be active while tasks exist. (Its an exception) -> https://stackoverflow.com/a/21998149/1925388 – Anmol Singh Jaggi May 29 '20 at 11:55

0 Answers0