Java Callable Future Example(java 关于Callable,Future的例子)

时间:2023-03-08 16:53:16
Home » Java » Java Callable Future Example

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 Future Example(java 关于Callable,Future的例子)

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

  1. 	<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( &quot;comment-42249&quot;, &quot;42249&quot;, &quot;respond&quot;, &quot;1090&quot; )" 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( &quot;comment-39722&quot;, &quot;39722&quot;, &quot;respond&quot;, &quot;1090&quot; )" 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.