Monday, June 30, 2014

Divide and Conquer technique is often used to solve many problems. The Problem is divided on the basis of size and that small size problem is solved and then merged accordingly to get the required solution. In a multi threaded environment using the feature of cuncurrency is the best option to get the better result from performance point of view.

Java 7 provides Fork/Join Framework for solving such kind of problem using threads. The best part of this framework like the executor framework it manages the creation and management of backends threads which actually executes your task. The framework also utilise the work stealing algorithm to improve performance this framework. The framework is designed in such a way that it's best suited for solving problem which requires the problem to divided into smaller tasks using divide and conquer technique.

Using ForkJoinPool and RecursiveTask class For Implementing Solution for finding sum of first 1000 natural number using divide and conquer approach

package read.java.thread.fork_joinframework;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;


class SumOfTen extends RecursiveTask{
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 int start;
 int end;
 
 public SumOfTen(int start,int end){
  this.start=start;
  this.end=end;
 }
 
 @Override
 protected Integer compute() {
  // TODO Auto-generated method stub
  if(end - start > 10){
   int mid = (start + end) / 2;
   SumOfTen task1=new SumOfTen(start, mid);
   SumOfTen task2=new SumOfTen(mid+1, end);
            invokeAll(task1,task2);
            int sum=0;
            try{
             sum = task1.get() + task2.get();
            }catch(Exception exp){
             exp.printStackTrace();
            }
            return sum;
  }else{
   return sum(start,end);
  }
 }
 
 
 private int sum(int start,int end){
  int sum=0;
  for(int i=start ; i <= end ; i++){
   sum+=i;
  }
  return sum;
 }

}



public class SumOfThousands {

 /**
  * @param args
  * @throws ExecutionException 
  * @throws InterruptedException 
  */
 public static void main(String[] args) throws InterruptedException, ExecutionException {
  // TODO Auto-generated method stub
  SumOfTen task=new SumOfTen(0,20);
  ForkJoinPool pool=new ForkJoinPool();
  pool.execute(task);
  
  do {
   System.out.printf("******************************************\n");
   System.out.printf("Main: Parallelism: %d\n",pool.getParallelism());
   System.out.printf("Main: Active Threads: %d\n",pool.getActiveThreadCount());
   System.out.printf("Main: Task Count: %d\n",pool.getQueuedTaskCount());
   System.out.printf("Main: Steal Count: %d\n",pool.getStealCount());
   System.out.printf("******************************************\n");
   try {
   TimeUnit.SECONDS.sleep(1);
   } catch (InterruptedException e) {
   e.printStackTrace();
   }
   } while (!task.isDone());
  
  
  System.out.println(task.get());
 }

}

Monday, June 23, 2014

Pessimistic Vs Optimistic Approach for Thread Safety.

For concurrent environment, Where numbers of threads playing with objects than can be used by them concurrently, is a possible case for data race, or dirty read. Developing a thread safe program is a tedious task, specially when you have no support from the environment or compiler itself for handling such a thing.

What is more important for an algorithm to work, it’s correctness. If your program is not correct then it is of no use. Hence from a programmer point of view, they mostly give correctness more importance than it’s performance.

Pessimistic Approach for Thread Safety

In java, for developing a multithreaded concurrent program with correct behaviour in any condition, there are the concept of intrinsic or extrinsic locks. We generally prefer thread safe class which internally uses this locking mechanism to implement so that it can guarantee thread safety. You and me have used synchronized keyword as well as certain synchronization tools like, Lock, Semaphore etc for creating thread safe class. But creating a thread safe class using these locking mechanism, have certain disadvantages also, it degrades your program also. Acquiring a lock, makes the requesting thread to go in waiting state during that period the thread will no be able to do anything also, no of context switching is required to wake the suspended and block the executing thread. Context switching is a costly operation. Sometimes it happens where you have a thread with high priority, but that thread will not be able to execute bcz, other thread have already acquired that lock. Hence this approach is sometimes not good from performance point of view, where there is less likely to be any conflict between threads running concurrently.

Using synchronized classes like StringBuffer, HashTable and other’s are totally thread safe, which used intrinsic locking mechanism to provide thread safety is based on Pessimistic Approach, which doesn’t take risk to conflict happens between thread by denying to do not work concurrently.

Optimistic Approach for Thread Safety

Optimisic approach is more towards, let the things happen we wiil manage it, if things like conflict occur. The best thing about this Approach is it’s performance. But the point which we have to handle this is, how we are going to handle this thing, if such kind of conflict happens.

    There are no of techniques, has been using for developing multi-threaded concurrent thread safe programs. Some of the strategies are
  • Compare And Swap
  • Copy On Write
  • Extrinsic Locks on Segments

There are numbers of Thread safe classes has been provided by java, which are implemented using such kind of strategy. These classes are part of or depends on java.util.concurrent package of java, which provides the framework for developing thread safe programs without using the instrinsic lock (Pessimistic Approach).


Thursday, June 19, 2014

Implementing Counting Semaphore Using Lock

Lock and Semphore is both a synchronization mechanism for multi-threaded environment. Both Lock and Semphore can be created by using each other. Lock can implemented using semaphore and semaphore can be implemented using Lock.

In this post, I have implemented a counting semaphore using Lock in java. A class Semphore is defined with instance member as Lock, Condition and integer. The Lock has been used to make the Semaphore class thread safe, and Condition variable is used as communication tool between the release() and acquire() method , and the integer variable permit is used to track, the no of permits as given to semaphore.

The acquire() method of the Semaphore has been implemented in such a way that, only for the allowed no of permits, thread is allowed to proceed, otherwise it will wait until the condition remain true i.e semaphore has been released by some other or same thread.

The release() method, simply acquire() the lock and then check for the permits count, if the permits count is greater than zero, means number of permits has already been granted to thread, hence it is safe for release(), i.e to increment the permit count and signal to waiting threads who are waiting for the semaphore permits using acquire() method, so that further thread can get permit using semaphore to proceed further.

package read.java.thread.semaphore;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


class Semaphore{
 
 int permits;
 Lock lock=new ReentrantLock();
 Condition condition=lock.newCondition();
 
 public Semaphore(int permits){
  this.permits=permits;
 }
 
 
 public void release() throws Exception{
  try{
   lock.lock();
   if(permits >= 0){
    permits++;
    System.out.println("Semaphore Released Notified to Others" + permits);
    condition.signalAll();
   }
  }catch(Exception exp){
   exp.printStackTrace();
   throw exp;
  }finally{
   lock.unlock();
   System.out.println("Semaphore Released Permit Count ===" + permits);
  }
 }
 
 
 public void acquire() throws InterruptedException{
  try{
   lock.lock();
   while(permits <= 0){
    System.out.println("Waiting for semaphore to obtain Permits =======" + permits);
    condition.await();
   }
   permits--;
  }catch(InterruptedException exp){
   throw exp;
  }
  finally{
   lock.unlock();
   System.out.println("Semaphore Acquired Permit Count ===" + permits);
  }
 } 
}




public class CountingSemaphoreUsingLock {

 
 public static void main(String[] args) throws Exception{
  Semaphore sem=new Semaphore(4);
  for(int i=0; i < 5 ; i++){
   sem.acquire();
  }
 }

}


Wednesday, June 18, 2014

When To Notify() and NotifyAll()

In a multi-threaded environment where several threads gonna executes tasks which might be not independent requires to communicate with each others, one of the common way used in java is using wait(), notify() and notifyAll().

When one of the thread is waiting for a condition to occur which resides in the condition queue requires to have get notification for the condition to occur. Other thread which is working something notify others thread that they have done their work means the condition is full filled and others can do their work. Generally programmers those who are novice to the working of notify() and notifyAll() simply calls notify() and thinks that their work is done...Hurrey.. But wait there is a technical gotcha.

There may be multiple threads waiting for the condition to occur for different condition predicate. calling notify() only wake up a single thread in the queue, the thread grabs the lock and check the condition it might happen that the condition is not for that thread, that thread again goes to the suspended state, but others thread will not be able to check for their case, and this might be a simple case of lost signal or signal hacking..

Using notifyAll() wakes all others threads which are in suspended state and hence no of threads comes to the running state, and one of the thread grabs the lock and check for their particular condition. This makes sure the correct working of your threaded program.

Friday, June 13, 2014

Installing and Configuring SendMail


During My application development i needed to send mail to our portal users.One of the option avalable for me to configure my own local system to as a MTA which can transfer email to destination smtp server which is my isp smtp server.

To make my system able to do that require job. We have installed the sendmail application to our local system on which my application is running by invoking the following command

$ apt-get install sendmail.

The command simply install the sendmail application to the system and make your system to work as a local smtp server. before getting your system to work fine, You have to configure your sendmail application to work as you expected. You just have to follow certain steps as i have mention below.


Step : 1
Edit /etc/mail/sendmail.mc file. and define the remote smtp server and it's domain by adding the following line of code

  define(`SMART_HOST', `yourremotesmtp.domain.in')dnl

Step : 2

To perform authentication to the remote smtp server. you have to create a authinfo file in the /etc/mail directory with the information regarding authentication to smtp server like your username and password. generally it will be your emailid and password to your mail service.

  create file /etc/mail/authinfo

  Add following information to the authinfo file

    AuthInfo: "U:youremail@domail.in" "P:password" "M:PLAIN"

  Add following section to /etc/mail/sendmail.mc file

        define(`confAUTH_OPTIONS', `A')dnl

        FEATURE(`authinfo',`hash -o /etc/mail/authinfo.db')dnl

  Enable your sendmail to route your email which has to be send by adding following lines

        MASQUERADE_AS(`yourdomainname.in')dnl

        MASQUERADE_DOMAIN(`yourdomainname.in')dnl

Step : 3

  Restart sendmail service.

  $service sendmail restart.

Step : 4

  Test your sendmail application by sending a test mail like.

        $ sendmail -v yourfriend@gmail.com.

        Test Email Message boby //new line

        . // terminate by dot(.)