Java Callable Future Example(java 关于Callable,Future的例子)
Java Callable Future Example
April 3, 2018 by Pankaj 25 Comments
Java Callable and Future are used a lot in multithreaded programming. In last few posts, we learned a lot about java threads but sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Java Callable

Java Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Java Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object.
Java Future
Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Java Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.
Here is a simple example of Java Callable task that returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Java Future to get the result of the submitted tasks.
Copy
package com.journaldev.threads;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
//return the thread name executing this callable task
return Thread.currentThread().getName();
}
public static void main(String args[]){
//Get ExecutorService from Executors utility class, thread pool size is 10
ExecutorService executor = Executors.newFixedThreadPool(10);
//create a list to hold the Future object associated with Callable
List<Future<String>> list = new ArrayList<Future<String>>();
//Create MyCallable instance
Callable<String> callable = new MyCallable();
for(int i=0; i< 100; i++){
//submit Callable tasks to be executed by thread pool
Future<String> future = executor.submit(callable);
//add Future to the list, we can get return value using Future
list.add(future);
}
for(Future<String> fut : list){
try {
//print the return value of Future, notice the output delay in console
// because Future.get() waits for task to get completed
System.out.println(new Date()+ "::"+fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
//shut down the executor service now
executor.shutdown();
}
}
Once we execute the above program, you will notice the delay in output because java Future get() method waits for the java callable task to complete. Also notice that there are only 10 threads executing these tasks.
Here is snippet of the output of above program.
Copy
Mon Dec 31 20:40:15 PST 2012::pool-1-thread-1
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
...
Tip: What if we want to override some of the methods of Java Future interface, for example overriding get() method to timeout after some default time rather than waiting indefinitely, in this case Java FutureTask class comes handy that is the base implementation of Future interface. Check out Java FutureTask Example to learn more about this class.
If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly. Recently I started creating video tutorials too, so do check out my videos on Youtube.
About Pankaj
Comments
<header class="comment-header">
<p class="comment-author" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
<span itemprop="name">Aakshi</span> <span class="says">says</span> </p> <p class="comment-meta"><time class="comment-time" datetime="2018-02-15T02:28:05+00:00" itemprop="datePublished"><a href="https://www.journaldev.com/1090/java-callable-future-example#comment-42249" class="comment-time-link" itemprop="url">February 15, 2018 at 2:28 am</a></time></p> </header> <div class="comment-content" itemprop="text"> <p>Thanks for the example.</p>
</div> <div class="comment-reply"><a rel="nofollow" class="comment-reply-link" href="#comment-42249" onclick="return addComment.moveForm( "comment-42249", "42249", "respond", "1090" )" aria-label="Reply to Aakshi">Reply</a></div> </article>
</li><!-- #comment-## --> <li class="comment odd alt thread-odd thread-alt depth-1" id="comment-39722">
<article itemprop="comment" itemscope="" itemtype="https://schema.org/Comment"> <header class="comment-header">
<p class="comment-author" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
<span itemprop="name">Shane</span> <span class="says">says</span> </p> <p class="comment-meta"><time class="comment-time" datetime="2017-10-13T15:00:30+00:00" itemprop="datePublished"><a href="https://www.journaldev.com/1090/java-callable-future-example#comment-39722" class="comment-time-link" itemprop="url">October 13, 2017 at 3:00 pm</a></time></p> </header> <div class="comment-content" itemprop="text"> <p>Thanks for this tutorial! I did have to make one modification.</p>
I changed (A) to (B) where:
(A) Future future = executor.submit(callable);
(B) Future future = executor.submit(new MyCallable());
<div class="comment-reply"><a rel="nofollow" class="comment-reply-link" href="#comment-39722" onclick="return addComment.moveForm( "comment-39722", "39722", "respond", "1090" )" aria-label="Reply to Shane">Reply</a></div>
</article>
</li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-38611">
<article itemprop="comment" itemscope="" itemtype="https://schema.org/Comment">
<header class="comment-header">
<p class="comment-author" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
<span itemprop="name">Utpal</span> <span class="says">says</span> </p>
<p class="comment-meta"><time class="comment-time" datetime="2017-07-10T03:31:21+00:00" itemprop="datePublished"><a href="https://www.journaldev.com/1090/java-callable-future-example#comment-38611" class="comment-time-link" itemprop="url">July 10, 2017 at 3:31 am</a></time></p> </header>
<div class="comment-content" itemprop="text">
<p>Thanks for sharing simple and understandable example.</p>
I have a question, it may be very silly but i want to clarify it with you.
In above example we will always get output as : pool-1-thread-(Number), where pool-1 is common, here my question is
since we have created pool of size 5. Output should also change accordingly like pool-1, pool-2 etc.
Java Callable Future Example(java 关于Callable,Future的例子)的更多相关文章
- Java线程:线程安全类和Callable与Future(有返回值的线程)
一.线程安全类 当一个类已经很好的同步以保护它的数据时,这个类就称为线程安全的.当一个集合是安全的,有两个线程在操作同一个集合对象,当第一个线程查询集合非空后,删除集合中所有元素的时候,第二个线程也来 ...
- Java Callable接口、Runable接口、Future接口
1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...
- Java并发机制(9)--Callable、Future、FutureTask的使用
Java并发编程:Callable.Future.FutureTask的使用 整理自:博客园-海子-http://www.cnblogs.com/dolphin0520/p/3949310.html ...
- java 多线程 33: 多线程组件之 Callable、Future和FutureTask
Callable Callable和rRunnable差不多,两者都是为那些其实例可能被另一个线程执行的类而设计的,最主要的差别在于Runnable不会返回线程运算结果,Callable可以(假如线程 ...
- Callable接口、Runable接口、Future接口
1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...
- [改善Java代码]异步运算考虑使用Callable接口
多线程有两种实现方式: 一种是实现Runnable接口,另一种是继承Thread类,这两种方式都有缺点,run方法没有返回值,不能抛出异常(这两个缺点归根到底是Runable接口的缺陷,Thread也 ...
- Java线程的创建方式三:Callable(四)
一.Java实现多线程的三种方式 方式一:继承Thread类: public class Test extends Thread { public static void main(String[] ...
- java多线程—Runnable、Thread、Callable区别
多线程编程优点 进程之间不能共享内存,但线程之间共享内存非常容易. 系统创建线程所分配的资源相对创建进程而言,代价非常小. Java中实现多线程有3种方法: 继承Thread类 实现Runnable接 ...
- Java并发编程-扩展可回调的Future
前提 最近在看JUC线程池java.util.concurrent.ThreadPoolExecutor的源码实现,其中了解到java.util.concurrent.Future的实现原理.从目前j ...
- Java多线程带返回值的Callable接口
Java多线程带返回值的Callable接口 在面试的时候,有时候是不是会遇到面试会问你,Java中实现多线程的方式有几种?你知道吗?你知道Java中有可以返回值的线程吗?在具体的用法你知道吗?如果两 ...
随机推荐
- js---10时间类
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- Gym 100952 H. Special Palindrome
http://codeforces.com/gym/100952/problem/H H. Special Palindrome time limit per test 1 second memory ...
- jq实现回车键执行方法
$(function(){ $(document).keypress(function (e){ if(e.keyCode == 13){ //执行你想执行的方法,keyCode代表不同的按键 } } ...
- syslog日志介绍
一. syslog简介 syslog是一种工业标准的协议,可用来记录设备的日志.在UNIX系统,路由器.交换机等网络设备中,系统日志(System Log)记录系统中任何时间发生的大小事件.管理者可以 ...
- python 中文文档地址总结
sqlalchemy: https://www.imooc.com/article/details/id/22343
- GetInvocationList 委托链表
最近发现C#程序初始化时在构造函数中,偶尔出现事件注册不成功.后查资料发现有GetInvocationList 这么一个获取类中的委托链表的函数, 使用方法如下: 1.在需委托的类(Class1)中增 ...
- Myeclipse学习总结(2)——MyEclipse快捷键大全
1.ctrl+shift+R 打开资源 此组快捷键可以打开工程中任意一个文件,而本人只需按文件名或者mask名的字母顺序输入就会出现对应的文件或者在内容中某个关键字再按快捷键也可以的,例如:Custo ...
- [React Native] Animate the Scale of a React Native Button using Animated.spring
In this lesson we will use Animated.spring and TouchableWithoutFeedback to animate the scale of a bu ...
- _00018 Hadoop-2.2.0 + Hbase-0.96.2 + Hive-0.13.1 分布式环境整合,Hadoop-2.X使用HA方式
博文作者:妳那伊抹微笑 itdog8 地址链接 : http://www.itdog8.com(个人链接) 博客地址:http://blog.csdn.net/u012185296 个性签名:世界上最 ...
- [51Nod]NOIP2018提高组省一冲奖班模测训练(一)题解
http://www.51nod.com/contest/problemList.html#!contestId=72&randomCode=147206 原题水题大赛.. A.珂朵莉的旅行 ...