Sunday, June 11, 2017

Multiple Locks to enhance application performance

Multiple Locks ; Using synchronized code blocks

public class Worker {
     private Random random = new Random();

     List<Integer> list1 = new ArrayList<Integer>();
     List<Integer> list2 = new ArrayList<Integer>();

     /* Thread 1 possess worker object lock while entering stageOne , thus thread2 can't enter stageTwo
      * although both threads are manipulating different data of an object */
    
     /*synchronized void statgeOne() throws InterruptedException {
     list1.add(random.nextInt(100));
     Thread.sleep(1);
     }

     synchronized void stageTwo() throws InterruptedException {
     list2.add(random.nextInt(100));
     Thread.sleep(1);
     }
      */

     /*Solution - We could have two different objects invoking different methods at once */
     Object obj1 = new Object();
     Object obj2= new Object();
    
     void statgeOne() throws InterruptedException {
           synchronized (obj1) {
                list1.add(random.nextInt(100));
                Thread.sleep(1);
           }
     }

     void stageTwo() throws InterruptedException {
           synchronized (obj2) {
                list2.add(random.nextInt(100));
                Thread.sleep(1);
           }
     }
     void process() throws InterruptedException{
           for(int i=0;i<1000;i++){
                statgeOne();
                stageTwo();
           }
     }
    
     public void main() throws InterruptedException {
           System.out.println("Starting ....");
          
           long start = System.currentTimeMillis();
          
           Thread t1= new Thread(new Runnable() {
                @Override
                public void run() {       
                try {
                     process();
                } catch (InterruptedException e) {
                     e.printStackTrace();
                     }
                }
           });
          
           Thread t2= new Thread(new Runnable() {
                @Override
                public void run() {       
                try {
                     process();
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
                }
           });
           t1.start();
           t2.start();
           t1.join();
           t2.join();
          
           long end = System.currentTimeMillis();
           System.out.println("List 1 size"+ list1.size()+"List 2 size "+ list2.size());
           System.out.println("Time taken :"+(end-start));
     }
}

Output

Starting ....
List 1 size 2000 
List 2 size 2000
Time taken :2862



No comments:

Post a Comment