Friday, September 18, 2015

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.




Sunday, May 31, 2015

Concurrent Programming Model in Android...

Note : Here are my two tutorials on Android Concurrency Model. Please have a look at these:
  1. https://youtu.be/zWdVVI7kH4E
  2. https://youtu.be/1J6iqKJgvDU
When an Android application is launched, the Android system creates a thread of execution for the application. This is known as the main thread. This is also known as the UI thread because all the android widgets used for this application run in the context of this main thread. Every UI thread will have its own looper by default which in association with a Message Queue is responsible for dispatching the user interface events to the appropriate widgets. This has been depicted in the following diagram:



We need to arrange our application components so that the UI thread always remains responsive.

Hence we cannot do a long running task like connecting to a network server and downloading a big file or doing a CRUD operation on a remote database in the main UI thread. if we do it then the long running task will block the UI thread and it will freeze the UI. Moreover, if the duration of this freezing of the UI thread is more than 5 seconds, we will get an "Application Not Responding" message which is not desirable. Hence we should do the long running task in a background UI thread.

Another important fact about Android is that the UI toolkit is not thread safe. Hence we cannot manipulate the UI thread from a background worker thread.

Thus there are simply two rules in Android application model vis-a-vis concurrency framework:

1. We should not block the UI thread
2. We should not manipulate the UI thread from a background thread.

Keeping in mind all these factors, there are mainly two ways of doing concurrent programming in Android:

1. Asynctask
2. Handler, Message & Runnable

This has been depicted in the following diagram.



Here are three different applications which show how we can write a concurrent program in Android and communicate to the main thread from a background thread.

You can browse/download the source code of these apps from here:

1. https://gitlab.com/som.mukhopadhyay/AsynctaskDownloadImage

2. https://gitlab.com/som.mukhopadhyay/DownloadImageWithRunnable

3. https://gitlab.com/som.mukhopadhyay/DownloadImageWithMessageHandler

The first has used an Asynctask, the second has used the function Activity.runOnUIThread and the third has used Handler & Message to achieve the same purpose.

Hopefully this will help you to understand the concurrent framework of Android.