Reason for calling shutdown () for ExecutorService

I've read quite a lot about this over the last couple of hours, and I just don't see any reason ( real reason) for calling shutdown() on the ExecutorService unless we have a huge application that stores, dozens and dozens of different executor services that are not used for a long time.

The only thing (from what I understood) that happens at the end of the job is to do what the normal thread does as soon as it does. When a regular thread completes the Runnable (or Callable) method, it will be passed to the garbage collector for collection. With the help of the Executor Service, threads will simply be suspended, they will not be marked for garbage collection. This requires a shutdown.

Ok, back to my question. Is there any reason to cause the shutdown of the ExecutorService to ExecutorService very often, or even immediately after giving it any tasks? I would like to leave behind the case when someone does this, and immediately after that calls awaitTermination() as it is checked. Once we do this, we must re-create a new ExecutorService to do the same. Isn't the whole idea for an ExecutorService reusing threads? So why destroy the ExecutorService so quickly?

Isn't that a rational way to just create an ExecutorService (or a couple depending on how much you need), then pass the tasks to them as soon as they appear, and then exit when you exit the application or at some other important stages. performers?

I would like to get an answer from some experienced programmers who write a lot of asynchronous code using ExecutorServices.

The second question, a little less deals with the Android platform. If some of you say that you should not close the artists each time, and you are programming on Android, could you tell us how you deal with these shutdowns (or rather, when you execute them) when we are dealing with various life events application loop.

Due to CommonsWare comment, I made the post neutral. I'm really not interested in arguing about it to death, and it seems to lead there. I'm only interested in what I asked experienced developers if they wanted to share their experience. Thank you

+66
java android executorservice
Apr 20 '13 at 17:09
source share
5 answers

The shutdown() method does one thing: prevents clients from sending more work to the executor service. This means that all existing tasks will be completed until completion, unless other actions are taken. This is true even for scheduled tasks, for example, for the ScheduledExecutorService: new instances of the scheduled task will not start. This can be useful in various scenarios.

Suppose you have a console application that has an executor service that performs N tasks. If the user presses CTRL-C, you expect the application to shut down, perhaps gracefully. What does it mean elegantly? Perhaps you want your application to not be able to submit more tasks to the executor’s service, and at the same time you want to wait for the completion of your existing N tasks. You can achieve this by using shutdown on shutdown as a last resort:

 final ExecutorService service = ... // get it somewhere Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("Performing some shutdown cleanup..."); service.shutdown(); while (true) { try { System.out.println("Waiting for the service to terminate..."); if (service.awaitTermination(5, TimeUnit.SECONDS)) { break; } } catch (InterruptedException e) { } } System.out.println("Done cleaning"); } })); 

This hook will disable a service that prevents your application from sending new tasks, and wait for all existing tasks to complete before shutting down the JVM. Completion of the wait will be blocked for 5 seconds and will return true if the service is disabled. This is done in a loop so that you are sure that the service will eventually shut down. InterruptedException is swallowed every time. This is the best way to shut down an artist service that is reused throughout the application.

This code is not perfect. If you are not sure that your tasks will eventually be completed, you can wait for a given timeout, and then just exit, leaving the threads running. In this case, it also makes sense to call shutdownNow() after a timeout in the last attempt to interrupt running threads ( shutdownNow() will also give you a list of tasks waiting to be started). If your tasks are designed to respond to interruptions, this will work just fine.

Another interesting scenario is when you have a ScheduledExecutorService that performs a periodic task. The only way to stop the chain of periodic tasks is to call shutdown() .

EDIT: I would like to add that I would not recommend using a disconnect hook, as shown above in the general case: it can be error prone and should only be a last resort. Moreover, if you have a lot of shutdown hooks registered, the order in which they are launched is undefined, which may be undesirable. I would prefer the application to explicitly call shutdown() on an InterruptedException .

+41
May 24 '13 at 19:21
source share

Isn't the whole idea for an ExecutorService reusing threads? So why destroy the ExecutorService so quickly?

Yes. You should not often destroy and recreate the ExecutorService . If necessary, initialize the ExecutorService (mainly at startup) and leave it active until you are done with it.

Isn't that a rational way to just create an ExecutorService (or a couple depending on how much you need), then pass the tasks to them as soon as they appear, and then exit when you exit the application or at some other important stages. performers?

Yes. It is rational to disable ExecutorService at important stages, such as exiting the application, etc.

The second question, a little less deals with the Android platform. If some of you say that it’s not a good idea to turn off artists each time, and you are programming on Android, could you tell me how you deal with these shutdowns (or rather, when you perform them) when we deal with different application events? life cycle.

Suppose that ExecutorService shared by various operations in your application. Each action will be paused / resumed at various intervals, and yet you will need one ExecutorService for your application.

Instead of managing the state of the ExecutorService in the Activity lifecycle methods, move the ExecutorService control (create / end) to your user service .

Create an ExecutorService in Service => onCreate() and correctly onDestroy() it in onDestroy()

Recommended way to shut down ExecutorService :

How to disable Java ExecutorService correctly

+6
Aug 26 '17 at 7:15
source share

The ExecutorService service must be closed when it is no longer necessary to free up system resources and allow the application to shut down correctly. Because threads in an ExecutorService may not be daemon threads, they can interfere with the normal shutdown of the application. In other words, your application continues to work after the completion of the main method.

Directory

Chaper: 14 Page: 814

+3
Apr 29 '18 at 20:34
source share

Reason for calling shutdown () in ExecutorService

Today I came across a situation where I need to wait until the machine is ready before starting a series of tasks on this machine.

I make a REST call to this computer, if I do not receive 503 (the server is unavailable), then the machine is ready to process my requests. So, I wait until I get 200 (Success) for the first REST call.

There are several ways to achieve it, I used ExecutorService to create a thread and scheduled it to start every X seconds. So, I need to stop this thread on condition, check this ...

 final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Runnable task = () -> { try { int statusCode = restHelper.firstRESTCall(); if (statusCode == 200) { executor.shutdown(); } } catch (Exception e) { e.printStackTrace(); } }; int retryAfter = 60; executor.scheduleAtFixedRate(task, 0, retryAfter, TimeUnit.SECONDS); 

Second question, slightly smaller deals with the Android platform.

Perhaps I can answer if you provide a little more context! Also from my Android development experience, you rarely need themes. Are you developing a game or application that needs threads for performance? If not, on Android you have other ways to solve problems such as the scenario described above. You can use TimerTask, AsyncTask, or Context-Based Handlers or Loaders. This is because if UIThread waits a long time, you know what happens: /

0
Sep 27 '17 at 10:43 on
source share

This is true, despite the planned events, for example, for the ScheduledExecutorService: new cases of the reserved appointment will not be executed.

We should expect that you have a comfortable application in which the agent administrator executes orders.

I did not catch the point without effort? You may need your application to not be able to send more agent administration appointments, and at the same time you need to sit back to complete N.'s current obligations.

Except when you are absolutely sure that your instructions will be in the end, you should sit back for this break, and after that just go out, leaving running strings.

If your activity is designed to respond to interference, this will work fine.

Another intriguing situation is when you have a ScheduledExecutorService that performs an action.

The best way to stop the chain of actions is to call shutdown ()

0
May 19 '19 at 5:37
source share



All Articles