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中有可以返回值的线程吗?在具体的用法你知道吗?如果两 ...
随机推荐
- Tiling POJ 2506 【大数】
id=2506">http://poj.org/problem?id=2506 Description In how many ways can you tile a 2xn rect ...
- Intel TBB in OpenCASCADE
Intel TBB in OpenCASCADE eryar@163.com OpenCASCADE使用了一个开源的第三方库Intel TBB,这个并行计算库主要用于网格化.布尔操作等复杂算法,可以明 ...
- intellij—idea14 注冊机
package com.qunar.fresh; import java.math.BigInteger; import java.util.Date; import java.util.Random ...
- Onvif开发之客户端搜索篇
关于ONVIF的广播,有客户端搜索和服务端发现的区别:客户端向固定的网段和固定的端口发送广播消息,服务端在对应的端口回复广播请求消息本文首先介绍客户端如何进行广播的已经对广播回复的信息的基本处理. 客 ...
- 64。node.js 中间件express-session使用详解
转自:http://jinjiakarl.com/2018/06/09/node-js-%E4%B8%AD%E9%97%B4%E4%BB%B6express-session%E4%BD%BF%E7%9 ...
- 转 EL表达式
EL表达式 一.EL表达式简介 EL 全名为Expression Language.EL主要作用: 1.获取数据 EL表达式主要用于替换JSP页面中的脚本表达式,以从各种类型的web域 中检索java ...
- 如何在canvas中画出一个太极图
先放一个效果图: 代码如下 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /&g ...
- python 数字计算模块 decimal(小数计算)
from decimal import * a = Decimal('0.1')+Decimal('0.1')+Decimal('0.1')+Decimal('0.3') float(a) >& ...
- 【Codeforces Round #456 (Div. 2) B】New Year's Eve
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 显然10000..取到之后 再取一个01111..就能异或成最大的数字了. [代码] /* 1.Shoud it use long ...
- 【Codeforces Round #428 (Div. 2) A】Arya and Bran
[Link]: [Description] [Solution] 傻逼题 [NumberOf WA] [Reviw] [Code] #include <bits/stdc++.h> usi ...