1

Look at the following piece of code:

     public void pinger()
     {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        executor.scheduleAtFixedRate(runnable, start, rate, TimeUnit.SECONDS);
        executor.shutdown();
     }

Is there any use of writing the shutdown command in this case? Different clients would create their own runnable objects and invoke this function.

User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
  • 1
    Why would you like to shutdown immediately after fixing a rate? – Yassin Hajaj May 25 '16 at 05:28
  • 1
    Please have a look at [Documentation](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#shutdown()) of this method. Creating new thread pool for each thread/runnable is not an advisable design. It can lead expensive use of resources. Think about sponsoring 1000 threads at a time. Thread pool should be just once with pool of 10 threads(as per resources available) in this case and use it globally for all requests. – Braj May 25 '16 at 05:50

2 Answers2

0

When you shutdown an executor, no new task will be accepted. Since you create a new one inside the pinger method every task has its own executor. A shutdown as you write will only free resource once the corrent task is terminated.

Hooch
  • 487
  • 3
  • 11
  • So when a new client with a new runnable object invokes the pinger() method, will it create issues, given the fact that the execution of the previous client was shutdown? – User_Targaryen May 25 '16 at 05:51
  • No, because you are creating a new executor for the new runnable. So the new task is indipendent from the one before. – Hooch May 25 '16 at 05:54
0

Some notes:

  1. You should not create Executor for each client request.
  2. Create Executor out side of client request and submit tasks to Executor
  3. When you decide that you should not accept new tasks to Executor, then shutdown the executor. The right way of shutting down Executor is explained in below post:

How to forcefully shutdown java ExecutorService

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211