Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

09_ Java FutureTask example _ 800+ Big Data & Java Interview FAQs

The document discusses the Java FutureTask, which is part of the concurrent package introduced in Java 5 for efficient multithreading. It explains the differences between Future and FutureTask, providing an example with two tasks: a short internal task and a long external task, demonstrating how to manage asynchronous computations. The example includes code snippets and highlights the importance of handling timeouts for long-running tasks.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

09_ Java FutureTask example _ 800+ Big Data & Java Interview FAQs

The document discusses the Java FutureTask, which is part of the concurrent package introduced in Java 5 for efficient multithreading. It explains the differences between Future and FutureTask, providing an example with two tasks: a short internal task and a long external task, demonstrating how to manage asynchronous computations. The example includes code snippets and highlights the importance of handling timeouts for long-running tasks.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs

800+ Q&As Menu Contact & reviews Register Login

800+ Big Data & Java Interview FAQs


It pays to prepare & choose from 2-6 offers. Read & Write more code to fast-track & go places with confidence.

Select A to Z of Java & Big Data Techs


search here … Go

Home Why?  Career  Membership 

Home › Java › 300+ Core Java Q&As › Core Java - Multithreading › 09: Java FutureTask example

09: Java FutureTask example 300+ Java Interview


Q&As - Quick Prep FAQs
 Posted on May 2, 2015
300+ Java Interview FAQs 📌 
Java 5 introduced the concurrent package for more efficient multi- 150+ Spring & Hibernate

FAQs
threading. 150+ Java Architect FAQs 📌 
100+ Java code quality Q&As
Q. What is the difference between Future and FutureTask in 
150+ Java coding Q&As
asynchronous processing? 
A. Future is the interface and FutureTask is the base implementation
of the Future with methods to start and cancel a computation. The
FutureTask provides asynchronous computation with methods to
start and cancel a computation, query to see if the computation is 300+ Big Data Interview
Q&As - Quick Prep FAQs
complete, and retrieve the result of the computation. The result can
only be retrieved when the computation has completed. The get
300+ Big Data Interview
method will block if the computation has not yet completed. Once FAQs 📌 

the computation has completed, the computation cannot be 250+ Scala Interview FAQs 
restarted or cancelled.
250+ Python interview
FAQs 📌 
Here is an example with 2 tasks. One is an internal short task that
takes ~1 second. The second task is an external long running task
taking 4 ~ 10 seconds. It is imperative that long running tasks need
to have proper processing timeouts. Key Areas & Companion
Techs FAQs

1 16+ Tech Key Areas FAQs 


2 import java.util.concurrent.Callable;
10+ Companion Tech Q&As 
3 import java.util.concurrent.ExecutionException;
4 import java.util.concurrent.ExecutorService;
5 import java.util.concurrent.Executors;
6 import java.util.concurrent.FutureTask;
7 import java.util.concurrent.TimeUnit;
8
9
import java.util.concurrent.TimeoutException;

https://www.java-success.com/java-futuretask-example/ 1/6
06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs
10 public class FutureTaskExample { 800+ Enterprise & Core
11 Java Q&As
12 // inner class
13 static class InternalProcess implements Callable<Integer> {
300+ Core Java Q&As 
14
15 @Override 300+ Enterprise Java Q&As 
16 public Integer call() throws Exception {
17
18 // just to simulate short internal process
19 TimeUnit.SECONDS.sleep(1);
20 return 2; Java & Big Data Tutorials
21 }
22
Tutorials - Golang 
23 }
24 Tutorials - Big Data 
25 // inner class
26 static class ExternalProcess implements Callable<Integer> { Tutorials - Enterprise Java 
27
28 @Override
29 public Integer call() throws Exception {
30 // just to simulate long running external process
31 TimeUnit.SECONDS.sleep(15);
32 return 12;
33 }
34 }
35
36 public static void main(String[] args) {
37 InternalProcess callable1 = new InternalProcess();
38 ExternalProcess callable2 = new ExternalProcess();
39
40 FutureTask<Integer> futureTask1 = new FutureTask<Integer>(
41 FutureTask<Integer> futureTask2 = new FutureTask<Integer>(
42
43 // create a fixed thread pool with 2 threads
44 ExecutorService executor = Executors.newFixedThreadPool(2)
45 // add future tasks to the pool
46 executor.execute(futureTask1);
47 executor.execute(futureTask2);
48
49 while (true) {
50 try {
51 if (futureTask1.isDone() && futureTask2.isDone()) {
52 System.out.println("Shutting down the executor.");
53 // shut down executor service
54 executor.shutdown();
55 return;
56 }
57
58 //if not done do it once
59 if (!futureTask1.isDone()) {
60 // wait indefinitely for future task to complete
61 System.out.println("Task1 output = " + futureTask1
62 }
63
64 System.out.println("Waiting for FutureTask2 to complete
65 //try the external task with the timeout of 5 seconds
66 Integer result = futureTask2.get(5, TimeUnit.SECONDS);
67 if (result != null) {
68 System.out.println("Task2 output = " + result);
69 } 
https://www.java-success.com/java-futuretask-example/ 2/6
06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs
70
71 } catch (InterruptedException ie) {
72 ie.printStackTrace();
73 } catch (TimeoutException e) {
74 // do nothing as we want to process it asynchronously
75 // if you want to time out then uncomment 2 lines
76
77 //System.out.println("Cancelling Task2 due to timeout")
78 //futureTask2.cancel(true); // true means interrupt
79 } catch (ExecutionException e) {
80 e.printStackTrace();
81 }
82 }
83 }
84
85 }
86

The output is

1
2 Task1 output = 2
3 Waiting for FutureTask2 to complete
4 Waiting for FutureTask2 to complete
5 Waiting for FutureTask2 to complete
6 Task2 output = 12
7 Shutting down the executor.
8

If you re-run it by uncommenting the last 2 lines in the


TimeoutException catch block, you will get task2 cancelled.

1
2 Task1 output = 2
3 Waiting for FutureTask2 to complete
4 Cancelling Task2 due to timeout
5 Shutting down the executor.
6

‹ Proxy design pattern in Java with service retry example

Graph from scratch Java example adjacent matrix approach ›

About Latest Posts

Arulkumaran Kumaraswamipillai

https://www.java-success.com/java-futuretask-example/ 3/6
06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs

Mechanical Engineer to self-taught Java engineer in 1999. Contracting since 2002 as a Java Engineer &
Architect and since 2016 as a Big Data Engineer & Architect. Preparation & key know-hows empowered me
to attend 150+ job interviews, choose from 130+ job offers & negotiate better contract rates. Author of the
book "Java/J2EE job interview companion", which sold 35K+ copies & superseded by this site with 3.5K+
registered users Amazon.com profile | Reviews | LinkedIn | LinkedIn Group | YouTube Email: java-
interview@hotmail.com

How to take the road less travelled?


Practicing & brushing up a few Q&As each day on broad number of main stream categories can make a huge impact in 3-12
months.

"You are paid to read & write lots of code & solve business problems in a
collaborative environment"
100+ Free Java Interview FAQs
100+ Free Big Data Interview FAQs

Don't be overwhelmed by the number of Q&As. Job interviews are not technical contests to see who gets most number of questions right.
Nobody knows everything. The Clarity of the answers you give with real-life examples will go a long way in getting you multiple job offers.
It pays to brush-up & choose from 2-6 job offers. Experienced interviewers can easily judge your real experience from a few open-ended
questions & the answers you provide.

If you are pressed for time, popular categories are pinned 📌


for you to prioritise based on the job description. Here are my top career
making know-hows & tips to open more doors as a Java/Big Data Engineer, Architect or Contractor.

1. Feeling stagnated?
2. How to earn more?
3. Freelancing Vs contracting?
4. Self-taught professional?
5. Job Interview Tips
6. Resume Writing Tips

Top 12 popular posts last 30 days


300+ Java Interview Q&As with code, scenarios & FAQs
300+ Core Java Interview Q&As 01. Ice breaker Tell us about yourself? 02. Ice Breaker 8 Java real life scenarios…
(6,825)

300+ Big Data Interview Q&As with code, scenarios & FAQs
100+ SQL Interview Q&As 01. 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code? 02.…
(2,425)

00: Top 50+ Core Java interview questions & answers for 1 to 3 years experience
Top 50 core Java interview questions covering core Java concepts with diagrams, code, examples, and scenarios. If you don't get…
(1,971)

Java 8 String streams and finding the first non repeated character with functional programming
Q1.Find the first non repeated character in a given string input using Java 8 or later? A1.Extends Find the first…

https://www.java-success.com/java-futuretask-example/ 4/6
06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs
(1,669)

18 Java scenarios based interview Q&As for the experienced – Part 1


Let's look at scenarios or problem statements & how would you go about handling those scenarios in Java. These scenarios…
(1,541)

Membership Levels
Membership prices listed below are in Australian Dollars (A$). If you purchase in other currencies like Indian rupees, the equivalent…
(718)

30+ Java Code Review Checklist Items


This Java code review checklist is not only useful during code reviews, but also to answer an important Java job…
(524)

8 real life Java scenarios with Situation-Action-Result (i.e. SAR) technique


The SAR (Situation-Action-Result) technique is very useful to tackle open-ended questions like: 1. What were some of the challenges you…
(522)

01: 30+ Java architect interview questions & answers – Part 1


One of the very frequently asked open-ended interview questions for anyone experienced is: Can you describe the high-level architecture of…
(480)

15 Ice breaker interview Q&As asked 90% of the time


Most interviews start with these 15 open-ended questions. These are ice breaker interview questions with no right or wrong answers…
(412)

0: 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code?
This extends 18+ SQL best practices & optimisation interview Q&As. You can practice these SQLs by setting up the data…
(370)

02: 10 Java String class interview Q&As


Java Collection interview questions and answers and Java String class interview questions and answers are must know for any Java…
(357)

Disclaimer
The contents in this Java-Success are copyrighted and from EmpoweringTech pty ltd. The EmpoweringTech pty ltd has the right to correct or enhance the current content without

any prior notice. These are general advice only, and one needs to take his/her own circumstances into consideration. The EmpoweringTech pty ltd will not be held liable for any

damages caused or alleged to be caused either directly or indirectly by these materials and resources. Any trademarked names or labels used in this blog remain the property of

their respective trademark owners. Links to external sites do not imply endorsement of the linked-to sites. Privacy Policy

© 2024 800+ Big Data & Java Interview FAQs 


Responsive WordPress Theme powered by CyberChimps

https://www.java-success.com/java-futuretask-example/ 5/6
06/12/2024, 19:39 09: Java FutureTask example | 800+ Big Data & Java Interview FAQs

Top


https://www.java-success.com/java-futuretask-example/ 6/6

You might also like