SlideShare a Scribd company logo
SOM-ITSOLUTIONS
Java
Java Concurrency Model - Future task
SOMENATH MUKHOPADHYAY
som-itsolutions
#A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282
Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com
Website:​ ​http://www.som-itsolutions.com/
Blog: ​www.som-itsolutions.blogspot.com
Note: Get the source code from ​https://github.com/sommukhopadhyay/FutureTask
Callables and Future
The FiutureTask is "A cancellable asynchronous computation. This class provides a base
implementation of Future, with methods to start and cancel a computation, query to see if the
computation is complete, and retrieve the result of the computation."
Callables are just like Runnables to define the smallest unit of work called tasks. The
difference between Callable and Runnable is that Runnable cannot return any result
whereas Callable can return result of type Future. Later we can get the data from this return
value.
Once we submit the Callable task to the Executor, it does not block and returns immediately.
We can determine if the task is finished or not by using the isDone api. Once isDone returns
TRUE, we can access the result from the future which was returned from submitting the task
to the executor using the future.get() API. However, we must remember that get API is
blocking and hence if the task is not completed when the get has been called, it will block the
thread.
ExecutorService
Actually FutureTask is designed to be used through the ExecutorService interface and the
classes that implement it. It is those classes that use FutureTask and fork the threads and
create non-blocking Asynchronous background task. Executors typically manage a pool of
threads so that we don't have to create threads manually. All the threads in a thread-pool
can be reused.
The source code mentioned below is a working example of the use of FutureTask alongwith
Executor model of the Java Concurrency Framework. The basic motto of the Application is
the following.
Suppose we need to do a very time consuming task at any time of an Application. Ay
reading a big chunk of data from a huge database. So the basic idea is that whenever the
application starts we spawn a background thread through the executor framework and
delegate the task of reading data to that background thread. While reading of the data is
going on, we continue with our other task in the application. The background thread collects
the data and keep it in the future variable which is returned when we submit the task to the
executor service. Any time of the application lifecycle we can know if the task is completed
or not by calling the api ​isDone()​ on the future returned from submitting the task. Then in
later time we can access the already fetched data by using the ​get()​ api on the future
variable which was returned when the task was submitted to the executor framework. Not
only that, when the task is going on in the background we can cancel it at anytime we want.
Hope this article comes handy to the learners of Java who are ready to deep dive in the
world of concurrent programming.
Class ProductInfo
package​ ​com.somitsolutions.training.java.ExperimentationWithFutureTask​;
public​ ​class​ ​ProductInfo​ ​{
​private​ String productName​;
​private​ ​float​ productPrice​;
​public​ ​ProductInfo​(​String productName​,​ ​float​ productPrice​){
​this​.​productName​ ​=​ productName​;
​this​.​productPrice​ ​=​ productPrice​;
​}
​public​ String ​getProductName​()​ ​{
​return​ productName​;
​}
​public​ ​void​ ​setProductName​(​String productName​)​ ​{
​this​.​productName​ ​=​ productName​;
​}
​public​ ​float​ ​getProductPrice​()​ ​{
​return​ productPrice​;
​}
​public​ ​void​ ​setProductPrice​(​float​ productPrice​)​ ​{
​this​.​productPrice​ ​=​ productPrice​;
​}
}
Class Preloader
package ​com.somitsolutions.training.java.ExperimentationWithFutureTask​;
import ​java.util.ArrayList​;
import ​java.util.List​;
import ​java.util.concurrent.ExecutionException​;
import ​java.util.concurrent.ExecutorService​;
import ​java.util.concurrent.Executors​;
import ​java.util.concurrent.FutureTask​;
import ​java.util.concurrent.Callable​;
public class ​Preloader​ ​{
static ExecutorService executor ​=​ Executors​.​newFixedThreadPool​(​1​);
List​<​ProductInfo​>​ productInfo ​=​ new ArrayList​<​ProductInfo​>();
//The difference between Callable & Runnable
//is that Callable can return a value (of type futuretask)
private FutureTask​<​List​<​ProductInfo​>>​ future ​=​ null​;
/*new FutureTask<List<ProductInfo>>(new LoadProductInfo());*/
public List​<​ProductInfo​>​ ​get​(){
//List<ProductInfo> retValue = null;
try ​{
//get is blocking
productInfo ​=​ future​.​get​();
}​ catch ​(​InterruptedException e​)​ ​{
// TODO Auto-generated catch block
e​.​printStackTrace​();
}​ catch ​(​ExecutionException e​)​ ​{
// TODO Auto-generated catch block
e​.​printStackTrace​();
}
return productInfo​;
}
public ​boolean​ ​cancel​(){
return future​.​cancel​(​true​);
}
public ​boolean​ ​isDone​(){
return future​.​isDone​();
}
//private final Thread thread = new Thread(future);
public ​void​ ​start​()​ ​{
System​.​out​.​println​(​"The task is being submitted now..."​);
//submit will return immediately. So we can do the other work
//in the main thread. Later we can check if the task is
//finished or not using isDone method.
future ​=​ ​(​FutureTask​<​List​<​ProductInfo​>>)​ ​(​executor​.​submit​(​new
LoadProductInfo​()));
}
//long running task
private List​<​ProductInfo​>​ ​loadProductInfo​(){
System​.​out​.​println​(​Thread​.​currentThread​().​getName​());
try ​{
Thread​.​sleep​(​10000​);
}​ catch ​(​InterruptedException e​)​ ​{
// TODO Auto-generated catch block
e​.​printStackTrace​();
}
//As if this data we have got from
//the database
for ​(​int​ i ​=​ ​0​;​ i​<​100000​;​ i​++){
ProductInfo productI ​=​ new
ProductInfo​(​Integer​.​toString​(​i​),​ i​);
productInfo​.​add​(​productI​);
}
return productInfo​;
}
//The difference between Callable & Runnable
//is that Callable can return a value (of type futuretask)
class ​LoadProductInfo​ implements Callable​<​List​<​ProductInfo​>>{
@Override
public List​<​ProductInfo​>​ ​call​()​ throws Exception ​{
// TODO Auto-generated method stub
return loadProductInfo​();
}
}
}
Class Main
package​ ​com.somitsolutions.training.java.ExperimentationWithFutureTask​;
import​ ​java.util.List​;
public​ ​class​ ​Main​ ​{
public​ ​static​ ​void​ ​main​(​String​[]​ args​){
List​<​ProductInfo​>​ listOfProductInfo ​=​ ​null​;
System​.​out​.​println​(​Thread​.​currentThread​().​getName​());
Preloader preloader ​=​ ​new​ Preloader​();
//start getting the data in a background thread and
//keep it for future use. while the background
//thread is getting the data, we will continue
//other task. later we can get this already fetched data
//using future.get method. remember this get API is blocking
preloader​.​start​();
/*//Do some other works... Here we are making the main thread sleep
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
int​ count ​=​ ​0​;
while​ ​(!​preloader​.​isDone​()){
System​.​out​.​println​(​"Task is yet to be completed..."​);
count​++;
try​ ​{
Thread​.​sleep​(​1000​);
}​ ​catch​ ​(​InterruptedException e​)​ ​{
// TODO Auto-generated catch block
e​.​printStackTrace​();
Preloader​.​executor​.​shutdown​();
System​.​exit​(​0​);
}​ ​//sleep for 1 millisecond before checking again
if​ ​(​count ​==​ ​100​){​//make the count == a low number say 8
//to see the cancellation effect
preloader​.​cancel​();
System​.​out​.​println​(​"The task has been cancelled..."​);
Preloader​.​executor​.​shutdown​();
System​.​exit​(​0​);
}
}
if​(!​preloader​.​cancel​()​ ​&&​ preloader​.​isDone​()){
listOfProductInfo ​=​ preloader​.​get​();
}
System​.​out​.​println​(​listOfProductInfo​.​get​(​0​).​getProductName​());
System​.​out​.​print​(​listOfProductInfo​.​get​(​0​).​getProductPrice​());
Preloader​.​executor​.​shutdown​();
}
}

More Related Content

PDF
The Mayans Lost Guide to RxJava on Android
PPTX
React hooks
PDF
How to build to do app using vue composition api and vuex 4 with typescript
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PDF
Java concurrency
PDF
RxJava@Android
PDF
Advanced Dagger talk from 360andev
PPTX
Adding a modern twist to legacy web applications
The Mayans Lost Guide to RxJava on Android
React hooks
How to build to do app using vue composition api and vuex 4 with typescript
The Future of Futures - A Talk About Java 8 CompletableFutures
Java concurrency
RxJava@Android
Advanced Dagger talk from 360andev
Adding a modern twist to legacy web applications

What's hot (20)

PPTX
Reactive Programming on Android - RxAndroid - RxJava
PDF
Understanding react hooks
PDF
Annotation Processing - Demystifying Java's Dark Arts
PDF
Concurrency and Thread-Safe Data Processing in Background Tasks
PPTX
React hooks
PPTX
2. Design patterns. part #2
PPTX
Java 8 - Completable Future
PDF
Fork Join (BeJUG 2012)
PPTX
React hooks
KEY
Fork/Join for Fun and Profit!
PPTX
Demystifying functional effect systems in Scala
PDF
Reactive Thinking in Java
PDF
How to build a react native app with the help of react native hooks
PDF
Deep dive into Android async operations
PDF
React js use contexts and useContext hook
PDF
Advanced JavaScript - Internship Presentation - Week6
PDF
Introduction to Retrofit and RxJava
PPTX
Understanding react hooks
PPTX
PPTX
Making React Native UI Components with Swift
Reactive Programming on Android - RxAndroid - RxJava
Understanding react hooks
Annotation Processing - Demystifying Java's Dark Arts
Concurrency and Thread-Safe Data Processing in Background Tasks
React hooks
2. Design patterns. part #2
Java 8 - Completable Future
Fork Join (BeJUG 2012)
React hooks
Fork/Join for Fun and Profit!
Demystifying functional effect systems in Scala
Reactive Thinking in Java
How to build a react native app with the help of react native hooks
Deep dive into Android async operations
React js use contexts and useContext hook
Advanced JavaScript - Internship Presentation - Week6
Introduction to Retrofit and RxJava
Understanding react hooks
Making React Native UI Components with Swift
Ad

Viewers also liked (15)

PPTX
RAKER PKP2A II LAN 2013 Oleh : Muskamal
PPT
Arca vigraha
PDF
Ict prabhuswamy m_jssie
PDF
Pelembagaan Balai Mediasi Penyelesaian Konflik
PDF
Memory layout in C++ vis a-vis polymorphism and padding bits
PDF
Ms1 seq 1 me and my friends ( 2 g)
PDF
Trabajo de Estadística.
PDF
Meeting aeltt teaching grammar algiers may 21st 2016
PDF
Social media : Type & Statistics
DOCX
Kliping gejala sosial
PDF
2 g ms1 level pre-sequence - now we have english
PPT
Evaluation assessment &amp; 2g curriculum a pril 26 2016
PPTX
Uml restaurant (group 1)
PDF
Teacher's handout test report and remedial work feb 2016
PDF
Cahier des Charges Infrastructure Informatique
RAKER PKP2A II LAN 2013 Oleh : Muskamal
Arca vigraha
Ict prabhuswamy m_jssie
Pelembagaan Balai Mediasi Penyelesaian Konflik
Memory layout in C++ vis a-vis polymorphism and padding bits
Ms1 seq 1 me and my friends ( 2 g)
Trabajo de Estadística.
Meeting aeltt teaching grammar algiers may 21st 2016
Social media : Type & Statistics
Kliping gejala sosial
2 g ms1 level pre-sequence - now we have english
Evaluation assessment &amp; 2g curriculum a pril 26 2016
Uml restaurant (group 1)
Teacher's handout test report and remedial work feb 2016
Cahier des Charges Infrastructure Informatique
Ad

Similar to Java concurrency model - The Future Task (20)

PPTX
Completable Future java 8 Features with example
ODP
Concurrent Programming in Java
PPTX
Lecture 23-24.pptx
PDF
Asynchronous programming with Java & Spring
PDF
Java Multithreading Using Executors Framework
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
PDF
Completable future
PPTX
Think Async in Java 8
PPTX
Multithreading and concurrency in android
PDF
Multithreading Introduction and Lifecyle of thread
PDF
Class notes(week 9) on multithreading
PDF
Leverage CompletableFutures to handle async queries. DevNexus 2022
PPT
cs4240-multithreading.ppt presentation on multi threading
PPT
Parallel programming
PDF
Concurrency-5.pdf
PPTX
Async java8
PPTX
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
PPTX
MULTITHREADING PROGRAMMING AND I/O THREAD
PPTX
Async task, threads, pools, and executors oh my!
PPTX
Multithreading.pptx
Completable Future java 8 Features with example
Concurrent Programming in Java
Lecture 23-24.pptx
Asynchronous programming with Java & Spring
Java Multithreading Using Executors Framework
Leveraging Completable Futures to handle your query results Asynchrhonously
Completable future
Think Async in Java 8
Multithreading and concurrency in android
Multithreading Introduction and Lifecyle of thread
Class notes(week 9) on multithreading
Leverage CompletableFutures to handle async queries. DevNexus 2022
cs4240-multithreading.ppt presentation on multi threading
Parallel programming
Concurrency-5.pdf
Async java8
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
MULTITHREADING PROGRAMMING AND I/O THREAD
Async task, threads, pools, and executors oh my!
Multithreading.pptx

More from Somenath Mukhopadhyay (20)

PDF
Significance of private inheritance in C++...
PDF
Arranging the words of a text lexicographically trie
PDF
Generic asynchronous HTTP utility for android
PDF
Copy on write
PDF
Developing an Android REST client to determine POI using asynctask and integr...
PDF
Observer pattern
PDF
Uml training
PDF
How to create your own background for google docs
PDF
The Designing of a Software System from scratch with the help of OOAD & UML -...
PDF
Structural Relationship between Content Resolver and Content Provider of Andr...
PDF
Flow of events during Media Player creation in Android
PDF
Implementation of a state machine for a longrunning background task in androi...
PDF
Tackling circular dependency in Java
PDF
Implementation of composite design pattern in android view and widgets
PDF
Exception Handling in the C++ Constructor
PDF
Active object of Symbian in the lights of client server architecture
PDF
Android services internals
PDF
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
PDF
Composite Pattern
PDF
Bridge Pattern
Significance of private inheritance in C++...
Arranging the words of a text lexicographically trie
Generic asynchronous HTTP utility for android
Copy on write
Developing an Android REST client to determine POI using asynctask and integr...
Observer pattern
Uml training
How to create your own background for google docs
The Designing of a Software System from scratch with the help of OOAD & UML -...
Structural Relationship between Content Resolver and Content Provider of Andr...
Flow of events during Media Player creation in Android
Implementation of a state machine for a longrunning background task in androi...
Tackling circular dependency in Java
Implementation of composite design pattern in android view and widgets
Exception Handling in the C++ Constructor
Active object of Symbian in the lights of client server architecture
Android services internals
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Composite Pattern
Bridge Pattern

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
1. Introduction to Computer Programming.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
A comparative analysis of optical character recognition models for extracting...
cuic standard and advanced reporting.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
Dropbox Q2 2025 Financial Results & Investor Presentation
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Assigned Numbers - 2025 - Bluetooth® Document
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Tartificialntelligence_presentation.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
1. Introduction to Computer Programming.pptx
Spectral efficient network and resource selection model in 5G networks
20250228 LYD VKU AI Blended-Learning.pptx
Unlocking AI with Model Context Protocol (MCP)
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A comparative analysis of optical character recognition models for extracting...

Java concurrency model - The Future Task

  • 1. SOM-ITSOLUTIONS Java Java Concurrency Model - Future task SOMENATH MUKHOPADHYAY som-itsolutions #A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282 Email: ​[email protected]​ / ​[email protected] Website:​ ​http://www.som-itsolutions.com/ Blog: ​www.som-itsolutions.blogspot.com
  • 2. Note: Get the source code from ​https://github.com/sommukhopadhyay/FutureTask Callables and Future The FiutureTask is "A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation." Callables are just like Runnables to define the smallest unit of work called tasks. The difference between Callable and Runnable is that Runnable cannot return any result whereas Callable can return result of type Future. Later we can get the data from this return value. Once we submit the Callable task to the Executor, it does not block and returns immediately. We can determine if the task is finished or not by using the isDone api. Once isDone returns TRUE, we can access the result from the future which was returned from submitting the task to the executor using the future.get() API. However, we must remember that get API is blocking and hence if the task is not completed when the get has been called, it will block the thread. ExecutorService Actually FutureTask is designed to be used through the ExecutorService interface and the classes that implement it. It is those classes that use FutureTask and fork the threads and create non-blocking Asynchronous background task. Executors typically manage a pool of threads so that we don't have to create threads manually. All the threads in a thread-pool can be reused. The source code mentioned below is a working example of the use of FutureTask alongwith Executor model of the Java Concurrency Framework. The basic motto of the Application is the following. Suppose we need to do a very time consuming task at any time of an Application. Ay reading a big chunk of data from a huge database. So the basic idea is that whenever the application starts we spawn a background thread through the executor framework and delegate the task of reading data to that background thread. While reading of the data is going on, we continue with our other task in the application. The background thread collects the data and keep it in the future variable which is returned when we submit the task to the executor service. Any time of the application lifecycle we can know if the task is completed or not by calling the api ​isDone()​ on the future returned from submitting the task. Then in later time we can access the already fetched data by using the ​get()​ api on the future
  • 3. variable which was returned when the task was submitted to the executor framework. Not only that, when the task is going on in the background we can cancel it at anytime we want. Hope this article comes handy to the learners of Java who are ready to deep dive in the world of concurrent programming. Class ProductInfo package​ ​com.somitsolutions.training.java.ExperimentationWithFutureTask​; public​ ​class​ ​ProductInfo​ ​{ ​private​ String productName​; ​private​ ​float​ productPrice​; ​public​ ​ProductInfo​(​String productName​,​ ​float​ productPrice​){ ​this​.​productName​ ​=​ productName​; ​this​.​productPrice​ ​=​ productPrice​; ​} ​public​ String ​getProductName​()​ ​{ ​return​ productName​; ​} ​public​ ​void​ ​setProductName​(​String productName​)​ ​{ ​this​.​productName​ ​=​ productName​; ​} ​public​ ​float​ ​getProductPrice​()​ ​{ ​return​ productPrice​; ​} ​public​ ​void​ ​setProductPrice​(​float​ productPrice​)​ ​{ ​this​.​productPrice​ ​=​ productPrice​; ​} } Class Preloader package ​com.somitsolutions.training.java.ExperimentationWithFutureTask​; import ​java.util.ArrayList​; import ​java.util.List​; import ​java.util.concurrent.ExecutionException​;
  • 4. import ​java.util.concurrent.ExecutorService​; import ​java.util.concurrent.Executors​; import ​java.util.concurrent.FutureTask​; import ​java.util.concurrent.Callable​; public class ​Preloader​ ​{ static ExecutorService executor ​=​ Executors​.​newFixedThreadPool​(​1​); List​<​ProductInfo​>​ productInfo ​=​ new ArrayList​<​ProductInfo​>(); //The difference between Callable & Runnable //is that Callable can return a value (of type futuretask) private FutureTask​<​List​<​ProductInfo​>>​ future ​=​ null​; /*new FutureTask<List<ProductInfo>>(new LoadProductInfo());*/ public List​<​ProductInfo​>​ ​get​(){ //List<ProductInfo> retValue = null; try ​{ //get is blocking productInfo ​=​ future​.​get​(); }​ catch ​(​InterruptedException e​)​ ​{ // TODO Auto-generated catch block e​.​printStackTrace​(); }​ catch ​(​ExecutionException e​)​ ​{ // TODO Auto-generated catch block e​.​printStackTrace​(); } return productInfo​; } public ​boolean​ ​cancel​(){ return future​.​cancel​(​true​); } public ​boolean​ ​isDone​(){ return future​.​isDone​(); } //private final Thread thread = new Thread(future); public ​void​ ​start​()​ ​{ System​.​out​.​println​(​"The task is being submitted now..."​); //submit will return immediately. So we can do the other work //in the main thread. Later we can check if the task is //finished or not using isDone method.
  • 5. future ​=​ ​(​FutureTask​<​List​<​ProductInfo​>>)​ ​(​executor​.​submit​(​new LoadProductInfo​())); } //long running task private List​<​ProductInfo​>​ ​loadProductInfo​(){ System​.​out​.​println​(​Thread​.​currentThread​().​getName​()); try ​{ Thread​.​sleep​(​10000​); }​ catch ​(​InterruptedException e​)​ ​{ // TODO Auto-generated catch block e​.​printStackTrace​(); } //As if this data we have got from //the database for ​(​int​ i ​=​ ​0​;​ i​<​100000​;​ i​++){ ProductInfo productI ​=​ new ProductInfo​(​Integer​.​toString​(​i​),​ i​); productInfo​.​add​(​productI​); } return productInfo​; } //The difference between Callable & Runnable //is that Callable can return a value (of type futuretask) class ​LoadProductInfo​ implements Callable​<​List​<​ProductInfo​>>{ @Override public List​<​ProductInfo​>​ ​call​()​ throws Exception ​{ // TODO Auto-generated method stub return loadProductInfo​(); } } } Class Main package​ ​com.somitsolutions.training.java.ExperimentationWithFutureTask​; import​ ​java.util.List​; public​ ​class​ ​Main​ ​{ public​ ​static​ ​void​ ​main​(​String​[]​ args​){ List​<​ProductInfo​>​ listOfProductInfo ​=​ ​null​;
  • 6. System​.​out​.​println​(​Thread​.​currentThread​().​getName​()); Preloader preloader ​=​ ​new​ Preloader​(); //start getting the data in a background thread and //keep it for future use. while the background //thread is getting the data, we will continue //other task. later we can get this already fetched data //using future.get method. remember this get API is blocking preloader​.​start​(); /*//Do some other works... Here we are making the main thread sleep try { Thread.sleep(50000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ int​ count ​=​ ​0​; while​ ​(!​preloader​.​isDone​()){ System​.​out​.​println​(​"Task is yet to be completed..."​); count​++; try​ ​{ Thread​.​sleep​(​1000​); }​ ​catch​ ​(​InterruptedException e​)​ ​{ // TODO Auto-generated catch block e​.​printStackTrace​(); Preloader​.​executor​.​shutdown​(); System​.​exit​(​0​); }​ ​//sleep for 1 millisecond before checking again if​ ​(​count ​==​ ​100​){​//make the count == a low number say 8 //to see the cancellation effect preloader​.​cancel​(); System​.​out​.​println​(​"The task has been cancelled..."​); Preloader​.​executor​.​shutdown​(); System​.​exit​(​0​); } } if​(!​preloader​.​cancel​()​ ​&&​ preloader​.​isDone​()){ listOfProductInfo ​=​ preloader​.​get​(); } System​.​out​.​println​(​listOfProductInfo​.​get​(​0​).​getProductName​());