{"id":6231,"date":"2019-03-17T20:30:49","date_gmt":"2019-03-17T20:30:49","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=6231"},"modified":"2019-03-21T12:16:44","modified_gmt":"2019-03-21T12:16:44","slug":"executorservice-based-multi-threading-in-java","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/executorservice-based-multi-threading-in-java\/","title":{"rendered":"ExecutorService based multi-threading in Java"},"content":{"rendered":"<p>A threading feature within Java is the ExecutorService. This allows us to, in essence, create our own threadpools. This is useful because it allows us to create a limited number of threads that our code may run on, ensuring we do not end up with thread starvation or the number of threads getting out of hand. <\/p>\n<p>By writing our code to use the ExecutorService we can also limit our methods to only use a single thread if we want.<\/p>\n<p>Here&#8217;s a simple example of using the ExectorService<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic static void main(String&#x5B;] args) throws \r\n   InterruptedException, \r\nExecutionException {\r\n\r\n   System.out.println(&quot;Main Thread - &quot; + Thread.currentThread().getId());\r\n\r\n   \/\/ExecutorService executorService = Executors.newSingleThreadExecutor();\r\n   ExecutorService executorService = \r\n      Executors.newFixedThreadPool(\r\n         Runtime.getRuntime().availableProcessors());\r\n\r\n   Future&lt;?&gt; f1 = executorService.submit(() \r\n      -&gt; outputInformation(1));\r\n   Future&lt;?&gt; f2 = executorService.submit(() \r\n      -&gt; outputInformation(2));\r\n   Future&lt;?&gt; f3 = executorService.submit(() \r\n      -&gt; outputInformation(3));\r\n\r\n   \/\/ the equivalent of waiting on the threads\r\n   f1.get();\r\n   f2.get();\r\n   f3.get();\r\n\r\n   executorService.shutdown();\r\n}\r\n\r\nprivate static void outputInformation(int id) {\r\n   try {\r\n      \/\/ some arbitrary time wasting\r\n      Thread.sleep(2000);\r\n      System.out.println(id + &quot; - &quot; + Thread.currentThread().getId());\r\n   }catch (Exception e) {\r\n   }\r\n}\r\n<\/pre>\n<p>In the code above, we are creating our own threadpool (using <em>Executors.newFixedThreadPool<\/em>) with the size based upon the number of available processors. Hence in this example (assuming you have more than 1 processor on your machine) the resulting output is indeterminant, i.e. we might see 2 followed by 1, followed by 3 and all on different threads. <\/p>\n<p>By simply changing to use <em>Executors.newSingleThreadExecutor()<\/em> the output will be in the correct order as only a single thread is used for each call.<\/p>\n<p>The ExecutorService is a useful abstraction for containing and controlling multiple threads.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A threading feature within Java is the ExecutorService. This allows us to, in essence, create our own threadpools. This is useful because it allows us to create a limited number of threads that our code may run on, ensuring we do not end up with thread starvation or the number of threads getting out of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[161,95],"tags":[],"class_list":["post-6231","post","type-post","status-publish","format-standard","hentry","category-java","category-multithreading"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/6231","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=6231"}],"version-history":[{"count":5,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/6231\/revisions"}],"predecessor-version":[{"id":6857,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/6231\/revisions\/6857"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=6231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=6231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=6231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}