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中有可以返回值的线程吗?在具体的用法你知道吗?如果两 ...
随机推荐
- scaleType-模拟按钮加文字整天点击效果
经常碰到这种情况,就是一个按钮下面有文字,我们点击按钮的时候,按钮跟文字的背景都是同时变化的.我们看下下面的效果 点击以后如下 如果想要实现这个方法,网上有很多的方法,主要就是自定义控件,或者是使用t ...
- 75.《nodejs开发指南》express4.x版-微博案例完整实现
转自:https://blog.csdn.net/cgwcgw_/article/details/39317587 完整代码下载 https://github.com/haishangfeie/wei ...
- 3.常用Bracket插件
转自:https://blog.csdn.net/iso_wsy/article/details/52608205 1.Emmet 如果你从事Web前端开发的话,对该插件一定不会陌生.它可以加快你的 ...
- vue ---- 组件传值之间使用 v-model
父子组件通信,都是单项的,很多时候需要双向通信.方法如下: 1.父组件使用:msg.sync="aa" 子组件使用$emit('update:msg', 'msg改变后的值xxx ...
- Intellij IDEA 部署Web项目,解决 404 错误
https://blog.csdn.net/eaphyy/article/details/72513914
- Vue给元素添加样式
Vue中使用样式 绑定css 数组 <style> .red{ color:red } .thin{ font-size:18px } </style> <h1 :cla ...
- Springboot2.0访问Redis集群
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作高性能的key-value数据库.缓存和消息中间件,掌握它是程序员的必备技能,下面是一个springboot访问redis的 ...
- 【Android Studio探索之路系列】之六:Android Studio加入依赖
作者:郭孝星 微博:郭孝星的新浪微博 邮箱:allenwells@163.com 博客:http://blog.csdn.net/allenwells github:https://github.co ...
- 14.NPM 常用命令
转自:http://www.runoob.com/nodejs/nodejs-npm.html PM提供了很多命令,例如install和publish,使用npm help可查看所有命令. NPM提供 ...
- 1.Node.js
转自:http://www.runoob.com/nodejs/nodejs-tutorial.html 简单的说 Node.js 就是运行在服务端的 JavaScript. Node.js 是一个基 ...