Skip to main content

Double check locking

Simple simulation of  muli-threading : few threads will read data from different sources and reduce them to get maximum from all the sources, An example of double check locking.

lets make a  prototype of above problem. we will not go and solve it for generic case, we will simply create two thread thread1 and thread2;  this two threads will read data from two different sources and will will use a shared variable to get maximum of two data sets. 

we will not go into details about what is singleton and double check locking, may be we see them in future post. in a sentence singleton is a design pattern that enable us to have only one   instantiation of an object. that means we can't create  object of that class using new when and when ever we need to have object.

So, our implementation logic goes as follows 
     1. start both the threads 
             find the max in each thread.
     next update the shared variable; the class which holds the shared variable is following singleton design pattern.




class ReduceNto1{

    int max=0;
    private static ReduceNto1 r1=null;
   
    public static  ReduceNto1 getInstance(){
        if(r1==null)                            
        {
            synchronized (ReduceNto1.class) {
                if(r1==null)
                r1=new ReduceNto1();
               
            }
       
        }
        return r1;
       
    }
   
    private ReduceNto1(){}
   
   
    public synchronized  void  setMax(int n){
   
       
        System.out.println("***"+n);
           
            if(n>max){
                max=n;
            }
           
       
    }   
       
   
   
    public int getMax(){
        return max;
    }

   
   
}

class MaxFinder implements  Runnable {

    int max=Integer.MIN_VALUE;
    int arr[];
   
    public MaxFinder(int arr[]){
        this.arr=arr;
    }
    public void run() {
      findMax();   
      System.out.println(max);
      System.out.println(Thread.currentThread().getName()+"****setting max from this thread to reduce*****"+max);
      ReduceNto1.getInstance().setMax(max);
     
    }


    public void findMax(){
       
       
        for(int i=0;i<arr.length;i++){
       
            if(arr[i]>max)
                max=arr[i];
        }
   
       
    }
   
    public int getMax(){
        return max;
    }
}



public class ConcurrentReadingFromNarray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        int arr1[]={1,2,3,4,5,49,7,8,9,10};
        int arr2[]={11,12,13,14,15,16,17,18,19,20};
        Thread t1=new Thread(new MaxFinder(arr1));
        Thread t2=new Thread(new MaxFinder(arr2));
        t1.start();
        t2.start();
        try{
            t1.join();
            t2.join();
        }catch(Exception e){}
        System.out.println("Max No is : "+ReduceNto1.getInstance().getMax());

    }

}
Output:
20
49
Thread-0****setting max from this thread to reduce*****49
Thread-1****setting max from this thread to reduce*****20
***20
***49
Max No is : 49

Note:

I am  prone to  typo; please report them and I will try to update the posts accordingly.

  

Comments

Popular posts from this blog

Greedy algorithms for Job Scheduling

In this programming problem and the next you'll code up the greedy algorithms from lecture for minimizing the weighted sum of completion times.. This file describes a set of jobs with positive and integral weights and lengths. It has the format [number_of_jobs] [job_1_weight] [job_1_length] [job_2_weight] [job_2_length] ... For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59. You should NOT assume that edge weights or lengths are distinct. Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order of the difference (weight - length). This algorithm is not always optimal. IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong answer. You should report the sum of weighted completion times of the resulting schedule --- a posi...

Integer comparison using == gets tricky between -128 to 127.

Integer i=45;                                                                                                                                   Integer k=45;         System.out.println("i.hashcode= "+i.hashCode());         System.out.println("k.hashcode= "+k.hashCode());         System.out.println(i==k);         System.out.println(i.equals(k)); Out Put: i.hashcode= 45 k.hashcode= 45 true true Great, it seems work fine! now change the value of i=k=201.         Integer i=201;     ...

You have given an array in which numbers are first increasing and then decreasing. Find the maximum element in O(log n).

An integer array with unique elements has the following property – elements initially are in increasing order till a point after which they start to decrease. Implement a function to find the index of the maximum element in the array in less than linear time, i.e., O(n). Example: Input: array = {1, 3, 5, 7, 9, 8, 6, 4} Output: max index = 4 Max Index : 4.  Max Element value is : 9