<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Suhas Bharadwaj</title>
    <description>The latest articles on DEV Community by Suhas Bharadwaj (@suhaspbharadwaj).</description>
    <link>https://dev.to/suhaspbharadwaj</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F110154%2F4d98a085-218b-4e1f-a2a7-3eb05575b4d4.jpeg</url>
      <title>DEV Community: Suhas Bharadwaj</title>
      <link>https://dev.to/suhaspbharadwaj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/suhaspbharadwaj"/>
    <language>en</language>
    <item>
      <title>Deep dive into Java Executor service framework - Part 1</title>
      <dc:creator>Suhas Bharadwaj</dc:creator>
      <pubDate>Fri, 21 Dec 2018 13:40:54 +0000</pubDate>
      <link>https://dev.to/suhaspbharadwaj/deep-dive-into-java-executor-service-framework---part-1-2ikd</link>
      <guid>https://dev.to/suhaspbharadwaj/deep-dive-into-java-executor-service-framework---part-1-2ikd</guid>
      <description>

&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;Hello folks! This is my first technical blog that am starting to write under my domain. I used to be an avid consumer of blog posts before, but it was time to move on to my own sweet space on the internet as a producer of content as I feel it is important to share my learnings with the community.&lt;/p&gt;

&lt;p&gt;Here is the &lt;a href="https://suhaspbharadwaj.com/executorservice"&gt;link&lt;/a&gt; to the original article !&lt;/p&gt;

&lt;p&gt;In this blog post, I'd like to cover in detail, the implementation of Executor Service framework released with the JDK 5. It is used to run the Runnable objects using concepts such as ThreadPool and ThreadFactory. &lt;/p&gt;

&lt;p&gt;If you are planning to implement some kind of concurrency in your project, I'd recommend for you to use higher level frameworks like this one, instead of going at it from scratch since that would ensure that your codebase is less affected by runtime datarace kind of situations and leave most of the heavy lifting of managing threads and synchronization to something that is more deterministic&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Executors.java Factory&lt;/li&gt;
&lt;li&gt;ExecutorService Interface&lt;/li&gt;
&lt;li&gt;ThreadPool Concept&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;1. Executors.java Factory
&lt;/h2&gt;

&lt;p&gt;The first thing that we do when we are using the Executor Service framework is to use the Executors factory class to return an instance of an object that implements all the methods of the ExecutorService interface. We call the public static threadpool instance creation methods on the constructor to get that specific wrapped ExecutorService implementation back. Once we get an instance of that service, we are in a positioned to submit tasks to the service and track the progress on each of those tasks. You can find this class under package &lt;code&gt;java.util.concurrent&lt;/code&gt;. Below is a sample snippet of achieving what I just discussed:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;ExecutorService&lt;/span&gt; &lt;span class="n"&gt;executorService&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Executors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;newFixedThreadPool&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;executorService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;Runnable&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Asynchronous task"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;});&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;executorService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;shutdown&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; 
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Different thread pools implementations that are instantiable from the Executors class are : &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fixed Thread Pool&lt;/strong&gt; : Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.  At any point, at most &lt;code&gt;nThreads&lt;/code&gt; will be active processing tasks. I'll be explaining in depth, in Part 2 of the series, the double click on this implementation&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Single Thread Executor&lt;/strong&gt; : Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. The returned executor is guaranteed not to be reconfigurable to use additional threads.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cached Thread Pool&lt;/strong&gt; : Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;2. ExecutorService Interface
&lt;/h2&gt;

&lt;p&gt;ExecutorService interface extends Executor interface which is an object that executes submitted &lt;code&gt;Runnable&lt;/code&gt; tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An &lt;code&gt;Executor&lt;/code&gt; is normally used instead of explicitly creating threads. For example, rather than invoking  &lt;code&gt;new Thread(new(RunnableTask())).start()&lt;/code&gt; for each of a set of tasks, you might use. Here is a concrete class that implements this interface : &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ThreadPerTaskExecutor&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="n"&gt;Executor&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
   &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Runnable&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
     &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Thread&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;start&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
   &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Sample of snippet of its invocation : &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;Executor&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;ThreadPerTaskExecutor&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;RunnableTask1&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;RunnableTask2&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Some of main methods from the ExecutorService interface that need to be implemented by the implementation classes are: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;void shutdown();&lt;/code&gt; : Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;List&amp;lt;Runnable&amp;gt; shutdownNow();&lt;/code&gt; : Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;boolean isShutdown();&lt;/code&gt; : Returns &lt;strong&gt;&lt;em&gt;true&lt;/em&gt;&lt;/strong&gt; if this executor has been shut down.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;boolean isTerminated();&lt;/code&gt; : Returns &lt;strong&gt;&lt;em&gt;true&lt;/em&gt;&lt;/strong&gt; if all tasks have completed following shut down.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;&lt;/code&gt; : Blocks until all tasks have completed execution after a shutdown * request, or the timeout occurs, or the current thread is interrupted, whichever happens first.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;&amp;lt;T&amp;gt; Future&amp;lt;T&amp;gt; submit(Callable&amp;lt;T&amp;gt; task);&lt;/code&gt; : Submits a value-returning task for execution and returns a  Future representing the pending results of the task. The  Future's &lt;code&gt;get&lt;/code&gt; method will return the task's result upon  successful completion.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;&amp;lt;T&amp;gt; Future&amp;lt;T&amp;gt; submit(Runnable task, T result);&lt;/code&gt; : Submits a Runnable task for execution and returns a Future  representing that task. The Future's &lt;code&gt;get&lt;/code&gt; method will  return the given result upon successful completion.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;&amp;lt;T&amp;gt; List&amp;lt;Future&amp;lt;T&amp;gt;&amp;gt; invokeAll(Collection&amp;lt;? extends Callable&amp;lt;T&amp;gt;&amp;gt; tasks) throws InterruptedException;&lt;/code&gt; : Executes the given tasks, returning a list of Futures holding  their status and results when all complete.  &lt;code&gt;Future#isDone&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; for each  element of the returned list.  Note that a &lt;strong&gt;&lt;em&gt;completed&lt;/em&gt;&lt;/strong&gt; task could have  terminated either normally or by throwing an exception.  The results of this method are undefined if the given  collection is modified while this operation is in progress.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;a&gt;&lt;/a&gt;3. Thread Pool Executor
&lt;/h2&gt;

&lt;p&gt;An implementation of the &lt;code&gt;ExecutorService&lt;/code&gt; that executes each submitted task using  one of possibly several pooled threads, normally configured  using &lt;code&gt;Executors&lt;/code&gt; factory methods. Thread pools address two different problems: they usually  provide improved performance when executing large numbers of  asynchronous tasks, due to reduced per-task invocation overhead,  and they provide a means of bounding and managing the resources,  including threads, consumed when executing a collection of tasks.  Each &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; also maintains some basic  statistics, such as the number of completed tasks.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ThreadPookExecutor&lt;/code&gt; extents the &lt;code&gt;AbstractExecutorService&lt;/code&gt; that again implements the &lt;code&gt;ExecutorService&lt;/code&gt; interface. &lt;/p&gt;

&lt;p&gt;The construction of the ThreadPoolExecutor takes in a few mandatory params to initialize in the right manner with the right strategy:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;  &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ThreadPoolExecutor&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;corePoolSize&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                              &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;maximumPoolSize&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                              &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;keepAliveTime&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                              &lt;span class="n"&gt;TimeUnit&lt;/span&gt; &lt;span class="n"&gt;unit&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                              &lt;span class="n"&gt;BlockingQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Runnable&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;workQueue&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;corePoolSize&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;maximumPoolSize&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepAliveTime&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;unit&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;workQueue&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
             &lt;span class="n"&gt;Executors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultThreadFactory&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;defaultHandler&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You might be wondering what the &lt;code&gt;corePoolSize&lt;/code&gt;, &lt;code&gt;maximumPoolSize&lt;/code&gt; and 'workQueue' are doing in this context. The &lt;code&gt;corePoolSize&lt;/code&gt; tells the &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; to initialize a default set of threads ready to pick up the next task that is submitted. The &lt;code&gt;workQueue&lt;/code&gt; is a BlockingQueue implementation data structure to queue the requests that exceed the &lt;code&gt;corePoolSize&lt;/code&gt; limit. Once &lt;code&gt;corePoolSize&lt;/code&gt; is reached, it starts to poll/take this queue for tasks and then schedule one of the existing threads to execute the task. This way, the thread pool executor manages to handle the thead resources in an efficient manner&lt;/p&gt;

&lt;h3&gt;
  
  
  Closing note
&lt;/h3&gt;

&lt;p&gt;This article is a &lt;em&gt;part 1&lt;/em&gt; of the &lt;em&gt;3 part series&lt;/em&gt; that I intend to publish. This gives a good understanding of the composition of the Executor Service framework implementation and some of the core ideas that make this framework easy and effective to use.&lt;/p&gt;

&lt;p&gt;If you have any queries or any constructive criticism to offer, leave it out in the comments below!&lt;/p&gt;


</description>
      <category>executors</category>
      <category>multithreading</category>
      <category>java</category>
      <category>threadpool</category>
    </item>
  </channel>
</rss>
