In modern software development, efficiently managing asynchronous tasks is essential for creating responsive applications. Java provides robust tools for handling concurrency through the java.util.concurrent package. One of the most useful components is the Future interface, which works with the ExecutorService to manage and retrieve the results of asynchronous computations. In this blog, we will delve into the details of Future and ExecutorService, providing comprehensive examples to illustrate their usage.
The Future interface holds the outcome of a computation that runs asynchronously. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result once it is available. If the computation hasn’t finished, the get method will block until it completes.
ExecutorService offers a higher-level abstraction for thread management than working directly with threads. It includes methods for handling termination and generating Future objects to track the progress of asynchronous tasks.
boolean cancel(boolean mayInterruptIfRunning): Tries to cancel the task execution.
boolean isCancelled(): Indicates whether the task was canceled before it finished.
boolean isDone(): Checks if the task has completed.
V get(): Waits if necessary for the computation to complete, and then retrieves its result.
V get(long timeout, TimeUnit unit): Waits for at most the given time for the computation to complete, and then retrieves its result.
You can create an ExecutorService using various factory methods in the Executors utility class, such as:
Let’s look at a practical example. We’ll create a simple task that performs a computation (e.g., calculating the sum of integers in an array) and use ExecutorService to execute it asynchronously.
First, let’s define a task that will perform the sum of an array of integers. We’ll create a class SumTask that implements the Callable interface. This class will be responsible for the actual computation.
import java.util.concurrent.Callable;
public class SumTask implements Callable<Integer> {
private final int[] numbers;
public SumTask(int[] numbers) {
this.numbers = numbers;
}
@Override
public Integer call() {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
}
Implementing Callable: The SumTask class implements the Callable interface, which allows it to return a result and throw a checked exception.
Constructor: The constructor accepts an array of integers, numbers, which will be summed.
Overriding call Method: The call method contains the logic for summing the integers in the array. It iterates through the array, calculates the sum, and returns it as an Integer.
Next, we’ll use the ExecutorService to execute the SumTask. This example demonstrates how to submit the task to an executor service and retrieve the result using a Future object.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureExample {
public static void main(String[] args) {
// Create an array of numbers to sum up
int[] numbers = {1, 2, 3, 4, 5};
// Create a SumTask
SumTask task = new SumTask(numbers);
// Create an ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();
// Submit the task to the executor
Future<Integer> future = executor.submit(task);
try {
// Get the result of the computation
Integer result = future.get();
System.out.println("Sum: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Shut down the executor
executor.shutdown();
}
}
}
🔹Creating the Task:
🔹Setting Up the ExecutorService:
🔹Submitting the Task:
🔹Retrieving the Result:
🔹Handling Exceptions:
🔹Shutting Down the ExecutorService:
Tasks can be canceled if they are no longer needed. This can be done using the cancel method of the Future interface.
Future<Integer> future = executor.submit(task);
if (!future.isDone()) {
future.cancel(true);
}
Let’s consider an example where we submit a task to the ExecutorService and retrieve the result with a specified timeout. This approach ensures that our application does not wait indefinitely for a task to complete.
You can specify a timeout for the get method to avoid waiting indefinitely.
Let’s explore an example where we submit a task to the ExecutorService and retrieve the result with a specified timeout. This method ensures that our application does not wait indefinitely for a task to complete.
Future<Integer> future = executor.submit(task);
try {
Integer result = future.get(1, TimeUnit.SECONDS);
System.out.println("Sum: " + result);
} catch (TimeoutException e) {
System.out.println("Task timed out");
}
Future<Integer> future = executor.submit(task);
🔹Submitting the Task:
Integer result = future.get(1, TimeUnit.SECONDS);
🔹Retrieving the Result with Timeout:
} catch (TimeoutException e) {
System.out.println("Task timed out");
}
🔹Handling TimeoutException:
🔹Key Points:
This approach is particularly useful in scenarios where tasks have variable execution times, and it’s critical to maintain application responsiveness by setting appropriate time limits on task completion.
This example demonstrates how to create and manage multiple asynchronous tasks using the ExecutorService and Future in Java. We will submit several tasks to the executor service, collect their Future objects, and then retrieve their results.
🔹Custom SumTask Class
First, we define a SumTask class that implements the Callable interface. This class will perform the task of summing an array of integers.
import java.util.concurrent.Callable;
public class SumTask implements Callable<Integer> {
private int[] numbers;
public SumTask(int[] numbers) {
this.numbers = numbers;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
}
🔹Main Class
Now, we create a main class that uses ExecutorService to submit multiple instances of SumTask and collects their results using Future.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
// Create a fixed thread pool with 10 threads
ExecutorService executor = Executors.newFixedThreadPool(10);
// List to hold Future objects
List<Future<Integer>> futures = new ArrayList<>();
// Submit tasks to the executor
for (int i = 0; i < 10; i++) {
int[] numbers = {i, i + 1, i + 2};
SumTask task = new SumTask(numbers);
futures.add(executor.submit(task));
}
// Retrieve and print the results
for (Future<Integer> future : futures) {
try {
Integer result = future.get(); // Blocking call, waits for the result
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
// Shutdown the executor
executor.shutdown();
}
}
Output:
Result: 3
Result: 6
Result: 9
Result: 12
Result: 15
Result: 18
Result: 21
Result: 24
Result: 27
Result: 30
🔹Defining the SumTask Class:
🔹Creating an ExecutorService:
ExecutorService executor =
Executors.newFixedThreadPool(10);
🔹Submitting Tasks to the ExecutorService:
for (int i = 0; i < 10; i++) {
int[] numbers = {i, i + 1, i + 2};
SumTask task = new SumTask(numbers);
futures.add(executor.submit(task));
}
🔹Retrieving and Printing the Results:
for (Future<Integer> future : futures) {
try {
Integer result = future.get(); // Blocking call, waits for the result
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
🔹Shutting Down the ExecutorService:
executor.shutdown();
Understanding and effectively using Future and ExecutorService in Java is essential for managing asynchronous tasks efficiently. By leveraging these tools, you can execute tasks concurrently, manage their execution, and retrieve their results in a robust and scalable manner. Whether you’re handling simple computations or complex parallel processing, these components of Java’s concurrency framework provide the necessary abstractions to make your code cleaner and more maintainable.
Feel free to try out the examples provided and experiment with different configurations of ExecutorService to better understand its capabilities and best practices. Happy coding!
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork