{"id":1820,"date":"2011-03-24T16:05:20","date_gmt":"2011-03-24T10:35:20","guid":{"rendered":"http:\/\/JitendraZaa.com\/blog\/?p=1820"},"modified":"2011-03-24T16:05:20","modified_gmt":"2011-03-24T10:35:20","slug":"java-threading-executor-framework-and-callable-interface","status":"publish","type":"post","link":"https:\/\/www.jitendrazaa.com\/blog\/java\/java-threading-executor-framework-and-callable-interface\/","title":{"rendered":"Java Threading &#8211; Executor Framework and Callable Interface"},"content":{"rendered":"<p>Executer is a concept evolved from the world of Runnable interface. We have seen that how to create a thread using <a title=\"Create Thread\" href=\"https:\/\/jitendrazaa.com\/blog\/java\/anonymous-classimplements-interface-methods-of-threads\/\" target=\"_blank\">Runnable interface, extending thread and anonymous classes<\/a>.<\/p>\n<p>To run the task by implementing Runnable interface, we must have to create the object of the Thread like new <em>thread(RunnableObject).start()<\/em>. \u00a0But we know that creating thread have its own overheads and stored in Stack and Heap memory.  It&#8217;s very expensive to create a thread object just only to run the task in separate thread.<\/p>\n<p><strong>Executors framework<\/strong> (java.util.concurrent.Executor), released by the JAVA 5 in package<em> java.util.concurrent<\/em> is used to run the Runnable thread objects without creating the Thread object.<\/p>\n<blockquote><p><strong>The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.<\/strong><\/p><\/blockquote>\n<p>There are three types of implementations provided by the Java:<\/p>\n<ol>\n<li><a title=\"ExecutorService\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/ExecutorService.html\" target=\"_blank\">ExecutorService<\/a><\/li>\n<li><a title=\"ThreadPoolExecutor\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/ThreadPoolExecutor.html\" target=\"_blank\">ThreadPoolExecutor<\/a><\/li>\n<li><a title=\"Class Executors\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/Executors.html\" target=\"_blank\">Executors<\/a> (A Class containing factory methods)<\/li>\n<\/ol>\n<p>To read documentation of Executor framework, refer this URL:<br \/>\n<a title=\"Executor Framework\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/Executor.html\" target=\"_blank\"> http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/Executor.html<\/a><\/p>\n<p><!--more-->It is beyond the scope of article to discuss about all the three implementations of the executor framework provided by the JAVA.<br \/>\nDemo of Using ExecutorService in Threading:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.G2.Thread;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\nclass SomeRunnable implements Runnable {\n\n\t@Override\n\tpublic void run() {\n\t\tfor (int i = 0; i &lt; 2; i++) {\n\t\t\tSystem.out.println(&quot;Counter - &quot; + i + &quot; \/ Thread Name : &quot;\n                        + Thread.currentThread().getName());\n\t\t}\n\t}\n\n}\n\npublic class ExecutorDemo {\n\tpublic static void main(String&#x5B;] args) {\n\t\t\/\/Create objects of Runnable\n\t\tSomeRunnable obj1 = new SomeRunnable();\n\t\tSomeRunnable obj2 = new SomeRunnable();\n\t\tSomeRunnable obj3 = new SomeRunnable();\n\n\t\t\/\/Create fixed Thread pool, here pool of 2 thread will created\n\t\tExecutorService pool = Executors.newFixedThreadPool(2);\n\n\t\tpool.execute(obj1);\n\t\tpool.execute(obj2);\n\t\tpool.execute(obj3);\n\n\t\tpool.shutdown();\n\t}\n\n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<blockquote><p>Counter &#8211; 0 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 0 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 0 \/ Thread Name : pool-1-thread-2<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-2<\/p><\/blockquote>\n<p>If the Threadpool is of size 3, that is if we change the line to :<br \/>\nExecutorService pool = Executors.newFixedThreadPool(3);<br \/>\n<strong>The output would look like:<\/strong><\/p>\n<blockquote><p>Counter &#8211; 0 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-1<br \/>\nCounter &#8211; 0 \/ Thread Name : pool-1-thread-3<br \/>\nCounter &#8211; 0 \/ Thread Name : pool-1-thread-2<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-2<br \/>\nCounter &#8211; 1 \/ Thread Name : pool-1-thread-3<\/p><\/blockquote>\n<hr \/>\n<p><span style=\"text-decoration: underline;\"><strong>Callable interface :<\/strong><\/span><\/p>\n<p>There are two disadvantages with using the Runnable interface in JAVA:<\/p>\n<ol>\n<li>Cannot return value from method run<\/li>\n<li>Cannot throw Checked Exception<\/li>\n<\/ol>\n<p>To overcome above problems, <em>java.util.concurrent<\/em> package has introduced the <strong>Callable interface<\/strong>. Instead of run() method, Callable interface defines single <strong>call()<\/strong> method, that <strong>takes no parameter but can throw exception<\/strong>.<br \/>\nAPI of Callable interface:<\/p>\n<p><a title=\"Callable Interface\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/Callable.html\" target=\"_blank\"> http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/concurrent\/Callable.html<\/a><br \/>\nBelow code demonstrates how to use the callable interface.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.G2.Thread;\n\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.FutureTask;\n\nclass MyCallable implements Callable&lt;Integer&gt; {\n\t@Override\n\tpublic Integer call() {\n\t\t\/\/ Demonstrates the autoboxing\n\t\treturn 111;\n\t}\n\n}\n\npublic class CallableDemo {\n\n\tpublic static void main(String&#x5B;] args) {\n\t\tFutureTask&lt;Integer&gt; task = new FutureTask&lt;Integer&gt;(new MyCallable());\n\t\tExecutorService pool = Executors.newSingleThreadExecutor();\n\t\tpool.submit(task);\n\t\ttry {\n\t\t\tSystem.out.println(&quot;Value returned from Thread : &quot; + task.get());\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (ExecutionException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tpool.shutdown();\n\t}\n}\n<\/pre>\n<p>Output:<\/p>\n<blockquote><p>Value returned from Thread : 111<\/p><\/blockquote>\n<p><strong>FutureTask<\/strong> class implements the<strong> interface Future<\/strong>. A Future represents the<strong> result of an asynchronous computation<\/strong>. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready.<br \/>\nTo read more on interface Future refer this URL: <a title=\"FutureTask in JAVA\" href=\"http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/util\/concurrent\/Future.html \" target=\"_blank\">http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/util\/concurrent\/Future.html <\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java Threading &#8211; Executor Framework and Callable Interface with example<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"jz_research_post":"","_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[3],"tags":[198],"class_list":["post-1820","post","type-post","status-publish","format-standard","hentry","category-java","tag-thread"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1825,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/java-thread-timertask\/","url_meta":{"origin":1820,"position":0},"title":"Java Thread &#8211; Executor framework, Timer and TimerTask","author":"Jitendra","date":"March 24, 2011","format":false,"excerpt":"Tutorial and example of Executor framework, Timer and TimerTask over Thread","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"Animation of ProgressBar in Swing Using TimerTask","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/03\/Animation-of-ProgressBar-Swing-Using-TimerTask.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":757,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/anonymous-classimplements-interface-methods-of-threads\/","url_meta":{"origin":1820,"position":1},"title":"Create Thread using Anonymous class and Interface","author":"Jitendra","date":"August 16, 2010","format":false,"excerpt":"Demonstration of creating Thread by Anonymous class and Interface","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":724,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/simple-threading-techniques\/","url_meta":{"origin":1820,"position":2},"title":"Thread, Life Cycle of Thread","author":"Jitendra","date":"August 7, 2010","format":false,"excerpt":"What is Thread? Life cycle of thread. Difference in start() and run() method of Thread. By Default how many thread runs?","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":847,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/mouse-handling-in-applets-using-this\/","url_meta":{"origin":1820,"position":3},"title":"Bouncing ball animation in Applet","author":"Jitendra","date":"August 25, 2010","format":false,"excerpt":"Example to show Bouncing ball animation in Applet","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"Mouse handling in applets using this pointer method, Bouncing ball","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2010\/08\/bOUNCINGBall.jpeg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":999,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/bouncing-ball-applet-create-balls-on-mouse-click-of-random-color-and-random-size\/","url_meta":{"origin":1820,"position":4},"title":"Bouncing ball applet &#8211; Create Balls on Mouse click of random color and random size","author":"Jitendra","date":"September 9, 2010","format":false,"excerpt":"Creating the balls on mouse click of random color, random size and random speed and bouncing around the wall of applet in JAVA.","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"Bouncing Ball applet - Create ball on Mouse click of random size and random color","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2010\/09\/Bouncing-Ball-applet.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":2422,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/quartz-framework-tutorial-with-example-schedule-job-in-java\/","url_meta":{"origin":1820,"position":5},"title":"Quartz framework tutorial with example &#8211; Schedule job in Java","author":"Jitendra","date":"September 22, 2011","format":false,"excerpt":"Tutorial of the Quartz framework for Java. Schedule job without loosing the performance of the application","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1820","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/comments?post=1820"}],"version-history":[{"count":0,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1820\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/media?parent=1820"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/categories?post=1820"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/tags?post=1820"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}