Friday, September 18, 2015

Java Concurrency Model - Part III - FutureTask

Note: Get the source code from https://gitlab.com/som.mukhopadhyay/FutureTask

In the last post we have seen about CoundownLatch. In this post i will discuss about FutureTask.

Callables & 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.

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>(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 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();
 }
}

Java Concurrency Model - Part II - CountDownLatch

Note: Get the source code from https://github.com/sommukhopadhyay/CountDownLatche

In this post i have tried to show an example using CountDownlatch, a synchronizer in Java concurrency framework.

Class CountDownLatchTest

package com.somitsolutions.training.java.ExperimentationWithCountdownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CountDownLatchTest {

    public static void main(String args[]) {
       final CountDownLatch latch = new CountDownLatch(3);
       Thread service1 = new Thread(new Service("Service1", 1000, latch));
       Thread service2 = new Thread(new Service("Service2", 1000, latch));
       Thread service3 = new Thread(new Service("Service3", 1000, latch));
      
       service1.start(); 
       service2.start(); 
       service3.start();
      
       // application should not start processing any thread until all service is up
       // and ready to do there job.
       // Countdown latch is idle choice here, main thread will start with count 3
       // and wait until count reaches zero. each thread once up and read will do
       // a count down. this will ensure that main thread is not started processing
       // until all services is up.
      
       //count is 3 since we have 3 Threads (Services)
      
       try{
            latch.await();  //main thread is waiting on CountDownLatch to finish
            System.out.println("All services are up, Application is starting now");
       }catch(InterruptedException ie){
           ie.printStackTrace();
       }
      
    }
  
}

/**
 * Service class which will be executed by Thread using CountDownLatch synchronizer.
 */
class Service implements Runnable{
    private final String name;
    private final int timeToStart;
    private final CountDownLatch latch;
  
    public Service(String name, int timeToStart, CountDownLatch latch){
        this.name = name;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }
  
    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println( name + " is Up");
        latch.countDown(); //reduce count of CountDownLatch by 1
    }
  
}

Java Concurrency Model - Part I - Producer Consumer Problem

Note: Get the source code from https://github.com/sommukhopadhyay/ProducerConsumer

As i was getting ready to teach Java Concurrency Model to my students, I have come up with few examples which i would like to share with you. The first example is about Producer Consumer problem. Here is the solution to this using wait and notify. In the next two posts we will see about CountDownLatch and FutureTask respectively.

Class ProducerConsumerQueue

package com.somitsolutions.training.java.ProducerConsumerProblem;

import java.util.Vector;

public class ProducerConsumerQueue {
 Vector<Integer> sharedQueue = new Vector<Integer>();
 private final int SIZE = 4;
 
 public ProducerConsumerQueue(){
 }
 
 public int getSIZE(){
  return SIZE;
 }
 
 public synchronized void produce(int i) throws InterruptedException{
  while(sharedQueue.size() == SIZE){
   System.out.println("Queue is full" + Thread.currentThread() + "is waiting, size = " + sharedQueue.size());
   wait();
  }
  sharedQueue.add(i);
  notifyAll();
 }
 
 public synchronized int consume() throws InterruptedException{
  while(sharedQueue.isEmpty()){
   
    System.out.println("Queue is empty " + Thread.currentThread().getName()
                        + " is waiting , size: " + sharedQueue.size());
    wait();
   }
  int retVal = sharedQueue.remove(0);
  notifyAll();
  return retVal;
 }
}

Class Producer

package com.somitsolutions.training.java.ProducerConsumerProblem;


public class Producer implements Runnable{
 private final ProducerConsumerQueue sharedQueue;
 private final int SIZE;
 
 public Producer(ProducerConsumerQueue queue){
  sharedQueue = queue;
  this.SIZE = sharedQueue.getSIZE();
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  for (int i = 0; i<7; i++){
   System.out.println("Produced: " + i);
   try{
    sharedQueue.produce(i);
    Thread.sleep(100);
   }
   catch (InterruptedException ex){
    
   }
  }
 }

}

Class Consumer

package com.somitsolutions.training.java.ProducerConsumerProblem;


public class Consumer implements Runnable{
 private final ProducerConsumerQueue sharedQueue;
 private final int SIZE;
 
 public Consumer(ProducerConsumerQueue queue){
  sharedQueue = queue;
  this.SIZE = sharedQueue.getSIZE();
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while (true){
   try{
    int val = sharedQueue.consume();
    System.out.println("Consumed:" + val);
    Thread.sleep(50); 
   }
   catch (InterruptedException ex){ 
   }
  }
 }

}

Class Main

package com.somitsolutions.training.java.ProducerConsumerProblem;

public class Main {
 public static void main(String[] args){
  ProducerConsumerQueue sharedQueue = new ProducerConsumerQueue();
  Thread prodThread = new Thread(new Producer(sharedQueue), "Producer");
        Thread consThread = new Thread(new Consumer(sharedQueue), "Consumer");
        prodThread.start();
        consThread.start();
 }
}

Monday, August 24, 2015

UML Training...

I know , the almighty has been testing me all through my professional life... Now there is a new dilemma that is haunting me everyday. This is should i make all my training materials online for others to access free of cost or not... i believe in free flow of knowledge... hence i have made all my Google play apps open source.... For me, it does not look good to earn money by sharing knowledge... knowledge should be free... that is why i like Google because they have democratized knowledge.... however, i have not picked up any skill other than software to support my family... and not only that i like sharing knowledge with others... hence the dilemma... but i can't stop listening to my heart... hence here goes another training material and its source code...

  i believe whoever is able to follow it, does not have to come to me... however, who does not follow and can pay a little bit, will surely come to me and make it a win-win situation... the supportive source code can be cloned from

Monday, July 20, 2015

Memory layout in C++ vis-a-vis Polymorphism and Padding bits

Monday, July 13, 2015

Android Graphics & Animation - a Bouncing Ball Game with source code

Note: For my live lecture of the training on Android Graphics & Animation, please have a look at

https://youtu.be/kRqsoApOr9U

https://youtu.be/Ji84HJ85FIQ

https://youtu.be/U8igPoyrUf8

Last week while conducting the summer training on Android & Java, one guy requested me to help develop an Android game. I thought the bouncing ball would be the perfect example through which we can show about Android graphics and animation. However, i would strongly suggest to use professionals Game engines like cocos-2d to develop real life Game apps.

This app is  simple yet will be able to clarify many things related to android graphics to the students. I have made this game opensource and one can clone the source code from the following link.
https://gitlab.com/som.mukhopadhyay/BouncingBall

Here is a screen recording of this app.





If this helps the Android learners, i would probably be the happiest guy.

Sunday, June 21, 2015

Memory Layout of Java Objects vis-a-vis Inheritance...

These two diagrams describe the memory layout of Java objects. This is with respect to inheritance and not from padding bits or alignment's point of view. To make it simple, i have omitted the methods from the Object class (the root class) in the VTBLE (also called method table). They will obviously occupy the first few indexes in each VTBLE in Java as all the classes are naturally derived from the Object class.