DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Java
  4. Java Executor Service Types

Java Executor Service Types

Eren Avsarogullari user avatar by
Eren Avsarogullari
·
Aug. 06, 12 · Interview
Like (2)
Save
Tweet
Share
22.18K Views

Join the DZone community and get the full member experience.

Join For Free
The ExecutorService feature came with Java 5. It extends the Executor interface and provides a thread pool feature to execute asynchronous short tasks.

There are five ways to execute the tasks asyncronously by using the ExecutorService interface provided Java 6.

ExecutorService execService = Executors.newCachedThreadPool();

This approach 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. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for 60 seconds are terminated and removed from the cache.

ExecutorService execService = Executors.newFixedThreadPool(10);

This approach creates a thread pool that reuses a fixed number of threads. Created nThreads will be active at the runtime. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

ExecutorService execService = Executors.newSingleThreadExecutor();

This approach creates an Executor that uses a single worker thread operating off an unbounded queue. Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.

Methods of the ExecutorService :

execute(Runnable) : Executes the given command at some time in the future.

submit(Runnable) : Submit method returns a Future Object which represents executed task. Future Object returns null if the task has finished correctly.

shutdown() : 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.

shutdownNow() : Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt, so any task that fails to respond to interrupts may never terminate.

A sample application is below :

STEP 1 : CREATE MAVEN PROJECT


A maven project is created as below. (It can be created by using Maven or IDE Plug-in).


STEP 2 : CREATE A NEW TASK


A new task is created by implementing the Runnable interface(creating Thread) as below. TestTask Class specifies business logic which will be executed.
package com.otv.task;

import org.apache.log4j.Logger;

/**
 * @author onlinetechvision.com
 * @since 24 Sept 2011
 * @version 1.0.0
 *
 */
public class TestTask implements Runnable {
 private static Logger log = Logger.getLogger(TestTask.class);
 private String taskName;

 public TestTask(String taskName) {
  this.taskName = taskName;
 }

 public void run() {
  try {
   log.debug(this.taskName + " is sleeping...");
   Thread.sleep(3000);
   log.debug(this.taskName + " is running...");
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

STEP 3 : CREATE TestExecutorService by using newCachedThreadPool


TestExecutorService is created by using the method newCachedThreadPool. In this case, created thread count is specified at the runtime.
package com.otv;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.otv.task.TestTask;

/**
 * @author onlinetechvision.com
 * @since 24 Sept 2011
 * @version 1.0.0
 *
 */
public class TestExecutorService {

 public static void main(String[] args) {
  ExecutorService execService = Executors.newCachedThreadPool();
  execService.execute(new TestTask("FirstTestTask"));
  execService.execute(new TestTask("SecondTestTask"));
  execService.execute(new TestTask("ThirdTestTask"));

  execService.shutdown();
 }
}
When TestExecutorService is run, the output will be seen as below :
24.09.2011 17:30:47 DEBUG (TestTask.java:21) - SecondTestTask is sleeping...
24.09.2011 17:30:47 DEBUG (TestTask.java:21) - ThirdTestTask is sleeping...
24.09.2011 17:30:47 DEBUG (TestTask.java:21) - FirstTestTask is sleeping...
24.09.2011 17:30:50 DEBUG (TestTask.java:23) - ThirdTestTask is running...
24.09.2011 17:30:50 DEBUG (TestTask.java:23) - FirstTestTask is running...
24.09.2011 17:30:50 DEBUG (TestTask.java:23) - SecondTestTask is running...

STEP 4 : CREATE TestExecutorService by using newFixedThreadPool


TestExecutorService is created by using the method newFixedThreadPool. In this case, required thread count has to be set as the following : 
package com.otv;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.otv.task.TestTask;

/**
 * @author onlinetechvision.com
 * @since 24 Sept 2011
 * @version 1.0.0
 *
 */
public class TestExecutorService {

 public static void main(String[] args) {
  ExecutorService execService = Executors.newFixedThreadPool(2);
  execService.execute(new TestTask("FirstTestTask"));
  execService.execute(new TestTask("SecondTestTask"));
  execService.execute(new TestTask("ThirdTestTask"));

  execService.shutdown();
 }
}
When TestExecutorService is run, ThirdTestTask is executed after FirstTestTask and SecondTestTask’ s executions are completed. The output will be seen as below:
24.09.2011 17:33:38 DEBUG (TestTask.java:21) - FirstTestTask is sleeping...
24.09.2011 17:33:38 DEBUG (TestTask.java:21) - SecondTestTask is sleeping...
24.09.2011 17:33:41 DEBUG (TestTask.java:23) - FirstTestTask is running...
24.09.2011 17:33:41 DEBUG (TestTask.java:23) - SecondTestTask is running...
24.09.2011 17:33:41 DEBUG (TestTask.java:21) - ThirdTestTask is sleeping...
24.09.2011 17:33:44 DEBUG (TestTask.java:23) - ThirdTestTask is running...

STEP 5 : CREATE TestExecutorService by using newSingleThreadExecutor


TestExecutorService is created by using the method newSingleThreadExecutor. In this case, only one thread is created and tasks are executed sequentially.
package com.otv;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.otv.task.TestTask;

/**
 * @author onlinetechvision.com
 * @since 24 Sept 2011
 * @version 1.0.0
 *
 */
public class TestExecutorService {

 public static void main(String[] args) {
  ExecutorService execService = Executors.newSingleThreadExecutor();
  execService.execute(new TestTask("FirstTestTask"));
  execService.execute(new TestTask("SecondTestTask"));
  execService.execute(new TestTask("ThirdTestTask"));

  execService.shutdown();
 }
}
When TestExecutorService is run, SecondTestTask and ThirdTestTask is executed after FirstTestTask’ s execution is completed. The output will be seen as below :
24.09.2011 17:38:21 DEBUG (TestTask.java:21) - FirstTestTask is sleeping...
24.09.2011 17:38:24 DEBUG (TestTask.java:23) - FirstTestTask is running...
24.09.2011 17:38:24 DEBUG (TestTask.java:21) - SecondTestTask is sleeping...
24.09.2011 17:38:27 DEBUG (TestTask.java:23) - SecondTestTask is running...
24.09.2011 17:38:27 DEBUG (TestTask.java:21) - ThirdTestTask is sleeping...
24.09.2011 17:38:30 DEBUG (TestTask.java:23) - ThirdTestTask is running...

STEP 6 : REFERENCES


http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
http://tutorials.jenkov.com/java-util-concurrent/executorservice.html


Task (computing) Java (programming language) Executor (software) Thread pool

Published at DZone with permission of Eren Avsarogullari, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Quest for REST
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • Top 5 Node.js REST API Frameworks
  • Why Every Fintech Company Needs DevOps

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: