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.
About Pankaj
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.
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中有可以返回值的线程吗?在具体的用法你知道吗?如果两 ...
随机推荐
- hdu 5073 Galaxy(2014 鞍山现场赛)
Galaxy Time Limit: 2000/1000 MS (J ...
- android 获取蓝牙已连接设备
蓝牙如果手动配对并已连接,获取连接的设备: 1.检测连接状态: int a2dp = bluetoothAdapter.getProfileConnectionState(BluetoothProfi ...
- 67.nodejs取参四种方法req.body,req.params,req.param,req.body
转自:http://www.cnblogs.com/jkingdom/p/8065202.html 摘要: nodejs取参四种方法req.body,req.params,req.param,req. ...
- C#开发 —— 高级应用
迭代器 可以返回相同类型的值的有序序列的一段代码,可用作方法,运算符或get访问器的代码体 使用 yield return 语句依次返回每个元素,yield break 语句可将终止迭代 迭代器的返回 ...
- SpringMVC-@RequestMapping的参数和用法
RequestMapping里面的注解包含的参数如图: RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上.用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径. ...
- POJ 1742 Coins 优化后的多重背包
Coins Time Limit: 3000MS Memory Limit: 30000K Total Submissions: 37853 Accepted: 12849 Descripti ...
- 趣题: 按二进制中1的个数枚举1~2^n (位运算技巧)
; ; k <= n; k++){ << k)-,u = << n; s < u;){ ;i < n;i++) printf(-i)&); print ...
- factor---将素数分解为质数
- PHP截取字符串长度
<?php function str_cut($string, $start=0,$length, $dot = '..') { $strlen = strlen($string); ...
- WPF中RichTextBox高度自适应问题解决方法
最近做一个项目需要用到RichTextBox来显示字符串,但是不允许出现滚动条,在RichTextBox宽度给定的条件下,RichTextBox的高度必须正好显示内容,而不出现下拉滚动条. 这样就要计 ...