Additional information about executors

In this chapter, we have extended ThreadPoolExecutor and the ScheduledThreadPoolExecutor class and overridden some of their methods. But you can override more methods if you want a more particular behavior. These are some methods you can override:

  • shutdown(): You must explicitly call this method to end the execution of the executor. You can override it to add some code to free additional resources used by your own executor.
  • shutdownNow(): The difference between shutdown() and shutdownNow() is that the shutdown() method waits for the finalization of all the tasks that are waiting in the executor.
  • submit(), invokeall(), or invokeany(): you call these methods to send concurrent tasks to the executor. You can override them if you need to do some actions before or after a task is inserted in the task queue of the executor. Note that adding a custom action before or after the task is enqueued is different than adding a custom action before or after it's executed, which we did while overriding beforeExecute() and afterExecute() methods.

In the news reader example, we use the scheduleWithFixedDelay() method to send tasks to the executor. But the ScheduledThreadPoolExecutor class has other methods to execute periodic tasks or tasks after a delay:

  • schedule(): This method executes a task after the given delay. The task is executed only once.
  • scheduleAtFixedRate(): This method executes a periodic task with the given period. The difference with the scheduleWithFixedDelay() method is that in the last one, the delay between two executions goes from the end of the first one to the start of the second one and in the first one the delay between two executions goes between the start of both.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.160.69