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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Build an MCP Server Using Go to Connect AI Agents With Databases
  1. DZone
  2. Coding
  3. Java
  4. Understand Java Callable and Future

Understand Java Callable and Future

A tutorial to help you understand how to use Callable and Future in Java.

By 
Shamik Mitra user avatar
Shamik Mitra
·
Aug. 28, 16 · Tutorial
Likes (22)
Comment
Save
Tweet
Share
229.5K Views

Join the DZone community and get the full member experience.

Join For Free

In Java multithreading programs, we extensively use Java Callable and Future. I believe all of you have the basic understanding of threads. In brief, The thread is a separate path of execution, so if you have to do a repetitive task, you can break the work into multiple chunks (tasks) and assign them to threads. Multiple Threads will execute tasks in parallel to get the result quickly.

In Java 5, java.util.concurrent was introduced. The callable interface was introduced in concurrency package, which is similar to the Runnable interface, but it can return any object, and is able to throw an Exception.

The Java Callable interface uses Generics, so it can return any type of Object. The Executor Framework offers a submit() method to execute Callable implementations in a thread pool. Actually, the Java Executor Framework follows WorkerThread patterns, wherein a thread pool you can initiate threads by using the  Executors.newFixedThreadPool(10); method. Then you can submit a task to it. As you may remember in Java, a runnable acts as the target of a thread, and in the runnable interface, a  public void run() method has to be implemented where you define the task, which will be executed by threads in the thread pool. The Executor Framework assigns work (runnable target) to threads only if there is an available thread in the pool. If all threads are in use, the work has to wait. Once a task is completed by the thread, that thread returns to the pool as an available thread. Callable is same as Runnable but it can return any type of Object if we want to get a result or status from work (callable).

Java Future

Java Callable tasks return java.util.concurrent.Future objects. Java Future provides a cancel() method to cancel the associated Callable task. This is an overloaded version of the get() method, where we can specify the time to wait for the result. It’s useful to avoid a current thread getting blocked for a longer time. Please note that the get method is a synchronous method. Until the callable finishes its task and returns a value, it will wait for a callable. There are also isDone() and isCancelled() methods to find out the current status of an associated Callable task.

Example: Suppose the problem is to find a sum of all numbers from 1 to 100. We can do it by looping 1 to 100 sequentially and adding them.

Another way we can do it by the divide and Conquer rule.  Group the numbers in a way so each group has exactly two elements. Then Assign that group to a pool of threads

So each thread returns a partial sum in parallel. Then collect those partial sums and add them to get the whole sum.

Image title

Code

Step 1: Create an Adder class and implement a callable to do the Partial sum on the group:

package com.example.thread.callable;
import java.util.concurrent.Callable;
publicclass CallableAdder implements Callable<Integer> {
       Integer operand1;
       Integer operand2;
       CallableAdder(Integer operand1,Integer operand2)
       {
             this.operand1=operand1;
             this.operand2=operand2;             
       }          
       public Integer call() throws Exception {
              // TODO Auto-generated method stub
              System.out.println(Thread.currentThread().getName()+" says : partial Sum for " + operand1 + " and "+ operand2+ " is "  +(operand1+operand2));
              return operand1+operand2;
       }
}

Step 2: Create a manager class, which is responsible for grouping integers, and submit the group to the Executor Framework for partial add. Collect the partial sum, wait until all partial sums return, and add them:

package com.example.thread.callable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ParallelAdder {                     
            public Integer parallelSum()
            {                       
                        //long t1 = System.currentTimeMillis();
                        ExecutorService executor = Executors.newFixedThreadPool(10);
                        List <Future<Integer>> list = new ArrayList<Future<Integer>>();
                        int count=1;
                        int prev=0;                       
                        for(int ;i<;i++)
                        {
                                    if(count%2=)//grouping
                                    {
                                                System.out.println("Prev :" + prev + " current: " + i);
                                                Future<Integer> future = executor.submit(new CallableAdder(prev,i));
                                                list.add(future);
                                                count=1;                                              
                                                continue;
                                    }
                                   prev=i ;
                                    count++;                                   
                        }
                        int totsum=0;                        
                        for(Future<Integer> fut : list)
                        {
                                    try {
                                                totsum = totsum+ fut.get();
                                    } catch (InterruptedException e) {                                               
                                                e.printStackTrace();
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                    } catch (ExecutionException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                    }
                        }                       
                        System.out.println("Total Sum is " + totsum);
                        //long t2 = System.currentTimeMillis();
                        //System.out.println("Time taken by parallelSum " + (t2-t1));
                        return totsum;                       
            }                     
            public int sequentialSum()
            {                      
                        //long t1 = System.currentTimeMillis();
                        Integer totsum=0;                        
                        for(int ;i<;i++)
                        {
                            totsum=totsum+i;                                               
                        }                       
                        //long t2 = System.currentTimeMillis();                       
                        System.out.println("sequentialSum Total Sum is " + totsum);
                        //System.out.println("Time taken by sequentialSum " + (t2-t1));
                        return totsum;
            }           
            public static void main(String[] args) {                       
                        ParallelAdder adder = new ParallelAdder();
                        int pSum= adder.parallelSum();
                        int sSum= adder.sequentialSum();                       
                        System.out.println("parallel Sum equals to Sequential Sum ? " );
                        System.out.println("Answer is :: " + (pSum==sSum));                                                                                          
            }
}

This is just a test example. The performance-wise Sequential sum is faster than the parallel sum.

Java (programming language)

Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!