SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Downloaden Sie, um offline zu lesen
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​();
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsJames Kirkbride
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Java 8 - Completable Future
Java 8 - Completable FutureJava 8 - Completable Future
Java 8 - Completable FutureSajad jafari
 
Demystifying functional effect systems in Scala
Demystifying  functional effect systems in ScalaDemystifying  functional effect systems in Scala
Demystifying functional effect systems in ScalaDmitry Karlinsky
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operationsMateusz Grzechociński
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Devang Garach
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaFabio Collini
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with SwiftRay Deck
 

Was ist angesagt? (20)

Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark Arts
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
React hooks
React hooksReact hooks
React hooks
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Java 8 - Completable Future
Java 8 - Completable FutureJava 8 - Completable Future
Java 8 - Completable Future
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
React hooks
React hooksReact hooks
React hooks
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 
Demystifying functional effect systems in Scala
Demystifying  functional effect systems in ScalaDemystifying  functional effect systems in Scala
Demystifying functional effect systems in Scala
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operations
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Spring boot
Spring bootSpring boot
Spring boot
 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with Swift
 

Andere mochten auch

RAKER PKP2A II LAN 2013 Oleh : Muskamal
RAKER PKP2A II LAN 2013 Oleh : MuskamalRAKER PKP2A II LAN 2013 Oleh : Muskamal
RAKER PKP2A II LAN 2013 Oleh : MuskamalMus kamal
 
Pelembagaan Balai Mediasi Penyelesaian Konflik
Pelembagaan Balai Mediasi Penyelesaian KonflikPelembagaan Balai Mediasi Penyelesaian Konflik
Pelembagaan Balai Mediasi Penyelesaian KonflikWasmui
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsSomenath Mukhopadhyay
 
Ms1 seq 1 me and my friends ( 2 g)
Ms1   seq 1  me and my friends ( 2 g)Ms1   seq 1  me and my friends ( 2 g)
Ms1 seq 1 me and my friends ( 2 g)Mr Bounab Samir
 
Meeting aeltt teaching grammar algiers may 21st 2016
Meeting aeltt  teaching grammar algiers may 21st 2016Meeting aeltt  teaching grammar algiers may 21st 2016
Meeting aeltt teaching grammar algiers may 21st 2016Mr Bounab Samir
 
Social media : Type & Statistics
Social media : Type & StatisticsSocial media : Type & Statistics
Social media : Type & StatisticsRahul Yadav
 
Kliping gejala sosial
Kliping gejala sosialKliping gejala sosial
Kliping gejala sosialAndi Uli
 
2 g ms1 level pre-sequence - now we have english
2 g    ms1 level  pre-sequence - now we have english2 g    ms1 level  pre-sequence - now we have english
2 g ms1 level pre-sequence - now we have englishMr Bounab Samir
 
Evaluation assessment &amp; 2g curriculum a pril 26 2016
Evaluation assessment &amp; 2g curriculum a pril 26 2016Evaluation assessment &amp; 2g curriculum a pril 26 2016
Evaluation assessment &amp; 2g curriculum a pril 26 2016Mr Bounab Samir
 
Teacher's handout test report and remedial work feb 2016
Teacher's handout test report and remedial work feb 2016Teacher's handout test report and remedial work feb 2016
Teacher's handout test report and remedial work feb 2016Mr Bounab Samir
 
Cahier des Charges Infrastructure Informatique
Cahier des Charges Infrastructure InformatiqueCahier des Charges Infrastructure Informatique
Cahier des Charges Infrastructure InformatiqueDATANYWARE.com
 

Andere mochten auch (15)

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

Ähnlich wie Java concurrency model - The Future Task

Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?Knoldus Inc.
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 

Ähnlich wie Java concurrency model - The Future Task (20)

Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Java bad coding practices
Java bad coding practicesJava bad coding practices
Java bad coding practices
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 

Mehr von Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trieSomenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidSomenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docsSomenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsSomenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureSomenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternSomenath Mukhopadhyay
 

Mehr von Somenath Mukhopadhyay (20)

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

Kürzlich hochgeladen

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Kürzlich hochgeladen (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

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: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com 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​());