Thursday, April 2, 2015

newCachedThreadPool example in Java

The first step to work with the Executor framework is to create an object of the ThreadPoolExecutor class. You can use the four constructors provided by that class or use a factory class named Executors that creates ThreadPoolExecutor. Once you have an executor, you can send Runnable or Callable objects to be executed. 
In this  article, you will learn how these two operations implement an example that will simulate a server processing requests from various clients. Before that you can have an overview of Executor frameworks in my previous article.



First, you have to implement the tasks that will be executed by the server. Create a class named Task that implements the Runnable interface


Now, implement the CachedPoolServer class that will execute every task it receives using an executor


Finally, implement the main class of the example by creating a class named Main and implement the main() method



How it works...
The main part of this example is the CachedPoolServer class. This class creates and uses ThreadPoolExecutor to execute tasks

The first important point is the creation of ThreadPoolExecutor in the constructor of the Server class. The ThreadPoolExecutor class has four different constructors but, due to their complexity, the Java concurrency API provides the Executors class to construct executors and other related objects. Although we can create  threadPoolExecutor directly using one of its constructors, it's recommended to use the Executors class.

In this case, you have created a cached thread pool using the newCachedThreadPool() method. This method returns an ExecutorService object, so it's been cast to ThreadPoolExecutor to have access to all its methods. The cached thread pool you have created creates new threads if needed to execute the new tasks, and reuses the existing ones if they have finished the execution of the task they were running, which are now available. The reutilization of threads has the advantage that it reduces the time taken for thread creation. The cached thread pool has, however, a disadvantage of constant lying threads for new tasks, so if you send too many tasks to this executor, you can overload the system

Tip
Use the executor created by the newCachedThreadPool() method only when you have a reasonable number of threads or when they have a short duration.

Once you have created the executor, you can send tasks of the Runnable or Callable type for execution using the execute() method. In this case, you send objects of  the Task class that implements the Runnable interface.

We also have printed some log messages with information about the executor. Specifically, you have used the following methods:

  • getPoolSize(): This method returns the actual number of threads in the pool of the executor
  • getActiveCount(): This method returns the number of threads that are executing tasks in the executor.
  • getCompletedTaskCount(): This method returns the number of tasks completed by the executor


One critical aspect of the ThreadPoolExecutor class, and of the executors in general, is that you have to end it explicitly. If you don't do this, the executor will continue its execution and the program won't end. If the executor doesn't have tasks to execute, it continues waiting for new tasks and it doesn't end its execution. A Java application won't end until all its non-daemon threads finish their execution, so, if you don't terminate the executor, your application will never end.


To indicate to the executor that you want to finish it, you can use the shutdown() method of the ThreadPoolExecutor class. When the executor finishes the execution of all pending tasks, it finishes its execution. After you call the shutdown() method, if you try to send another task to the executor, it will be rejected and the executor will throw a RejectedExecutionException exception. The following screenshot shows part of one execution of this example:




There's more...
The ThreadPoolExecutor class provides a lot of methods to obtain information about its status. We used in the example the getPoolSize(), getActiveCount(), and getCompletedTaskCount() methods to obtain information about the size of the pool, the number of threads, and the number of completed tasks of the executor. You can also use the getLargestPoolSize() method that returns the maximum number of threads that has been in the pool at a time.

  • shutdownNow(): This method shut downs the executor immediately. It doesn't execute the pending tasks. It returns a list with all these pending tasks. The tasks that are running when you call this method continue with their execution, but the method doesn't wait for their finalization.
  • isTerminated(): This method returns true if you have called the shutdown() or shutdownNow() methods and the executor finishes the process of shutting it down.
  • isShutdown(): This method returns true if you have called the shutdown() method of the executor.
  • awaitTermination(long timeout, TimeUnit unit): This method blocks the calling thread until the tasks of the executor have ended or the timeout occurs. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS


That's all. Thanks for reading this and if you found this article useful, I would like to see your appreciation in the form of comments.



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

25 comments:

  1. Thank you so much for the informative article share with us Jobs in Java

    ReplyDelete
  2. Thanks for sharing this good blog.This is very important and imformative blog for Java . very interesting and useful for students
    Java Online Training Hyderabd

    ReplyDelete
  3. Nice tutorial. Thanks for sharing the valuable info about Core java Training. it’s really helpful. Keep sharing on updated tutorials…..

    ReplyDelete
  4. Thanks for sharing such basic and informative blog.
    Java Training in Noida

    ReplyDelete
  5. Thank you for your post. This is excellent information. It is amazing, I wonderful to visit your Blog.
    iphone job Oriented course
    Mobile App Training Institutes

    ReplyDelete
  6. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    java training in chennai

    ReplyDelete
  7. I am glad to absorb this knowledge from you. Truly important and considerable details shared by you. The thing I like about your blog is that you post very relevant details about the topic you choose, which makes it very interesting and informative. Thank you for the share. Keep blogging
    Web Design Company | Web development Lucknow

    ReplyDelete
  8. very nice post, you have mentioned a very good points here, thanks for sharing!
    DevOps Online Training

    ReplyDelete
  9. Thanks for sharing this information.
    Learn Digital Academy is Digital marketing training in Bangalore . This course is in-class training.

    ReplyDelete
  10. Very interesting blog Awesome post. your article is really informative and helpful for me and other bloggers too

    Workday Online Training

    ReplyDelete
  11. Thanks for providing a knowledgeable articles keep it up. If you are facing some technical errors with Quicken on your Mac computer device than call on Quicken Customer Support Number and contact with the expertise to resolve the error.

    ReplyDelete
  12. Worth reading this article... Keep rocking. Implement SharePoint online from veelead solutions

    ReplyDelete
  13. Thanks for Sharing This Article. It is very so much valuable content. I hope these Commenting lists will help to my website Top 10 Makeup Artists in Kolkata

    ReplyDelete
  14. One benefit of making a String immutable is that it saves memory. When your application expands, the number of String instances it produces grows as well, and if you don't cache String constants, you'll wind up with a heap full of String. JVM saves a lot of memory for real-world design development Java programs by caching and sharing String constants.

    ReplyDelete
  15. https://rentbusdubai.com/ thanks for sharing

    ReplyDelete
  16. Purchasing instant YouTube subscribers propels your channel into the spotlight, instantly boosting its visibility and appeal. This method is a quick and efficient way to elevate your online presence on a global platform, ensuring your content reaches a wider audience. With diverse, budget-friendly packages available, this strategy is accessible to creators of all sizes, allowing for flexibility and financial ease. A secure and straightforward process guarantees a hassle-free experience, putting your mind at ease and letting you focus on content creation. This surge in subscriber count enhances your channel's credibility, attracting more viewers and potential collaborators, laying the groundwork for organic growth and community engagement. It's an investment in your digital future, creating a foundation for sustained success and recognition within the competitive YouTube landscape.
    https://www.buyyoutubesubscribers.in/

    ReplyDelete