UrbanPro
true

Learn Advanced Java coaching from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Java Concurrency Model - Future Task...

Somenath Mukhopadhyay
03/04/2017 0 0

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. Like 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>(new LoadProductInfo());*/


public List<ProductInfo>
get(){
//List 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

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Create Immutable Class
Snippet of an Immutable Class: package com.stringhr; /*Declare the class as 'final'. This would prevent any other class from extending it and hence from overriding any method from it which could modify...

Benefits of Design Patterns in Application Development
Application developments is a tedious job. Programmers write code and test it again and again to make sure their software works fine. So designing complex software is a hard nut to crack. Skilled programmers...

Best way to learn any software Course
Hi First conform whether you are learning from a real time consultant. Get some Case Studies from the consultant and try to complete with the help of google not with consultant. Because in real time same situation will arise. Thank you

Fractional Knapsack
Algorithm - Fractional Knapsack import java.util.Scanner; public class Knapsack01 { public static void main(String args) { Scanner scan = new Scanner(System.in); int...

EFFECTIVE TASKS & RESPONSIBILITIES DELEGATION
Do you feel your business relies too much on you? In working with business owners, there are a couple of tools we introduce to productively shift the workload and responsibility across the organization....
X

Looking for Advanced Java coaching Classes?

The best tutors for Advanced Java coaching Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Advanced Java coaching with the Best Tutors

The best Tutors for Advanced Java coaching Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more