Solved

Plz explain this program..

Posted on 2009-07-10
6
197 Views
Last Modified: 2013-11-23
Here in this program there is a static lock, which is a lock on a class, so at a time only lock1 or lock2 can be attained. So i am not understanding the output:

public class MyClass extends Thread{
      static Object lock1 = new Object();
      static Object lock2 = new Object();

      static volatile int i1, i2, j1, j2, k1, k2;

      public void run(){
            while(true){
                  doIt();
                  check();
            }
      }
      
      void doIt(){
            synchronized(lock1){ System.out.print(Thread.currentThread().getName()); i1++; }
            j1++;
            synchronized(lock2){ System.out.print(Thread.currentThread().getName()); k1++; k2++; }
            j2++;
            synchronized(lock1){ System.out.print(Thread.currentThread().getName()); i2++; }
      }

      void check(){
            try{
                  Thread.sleep(100);
                  if(i1 != i2) System.out.print("i1" + i1 + "i2" + i2);
                  else System.out.print("not i" + i1 + "not i2" + i2);
            }catch(InterruptedException e){}
            
            try{
                  Thread.sleep(100);
                  if(j1 != j2) System.out.print("j1" + j1 + "j2" + j2);
                  else System.out.print("not j1" + j1 + "not j2" + j2);
            }catch(InterruptedException e){}
                        try{
                  Thread.sleep(100);
                  if(k1 != k2) System.out.print("k1" + k1 + "k2" + k2);
                  else System.out.print("not k1" + k1 + "not k2" + k2);
            }catch(InterruptedException e){}
            
      }

      public static void main(String... args){
            new Thread(new MyClass(),"First Thread").start();
            //new Thread(new MyClass(), "Second Thread").start();      
      }
}
      
0
Comment
Question by:SunScreenCert
  • 3
  • 3
6 Comments
 
LVL 23

Assisted Solution

by:Ajay-Singh
Ajay-Singh earned 500 total points
ID: 24825089
> so at a time only lock1 or lock2 can be attained.

This is *not* true. Since lock1, and lock2 are two different objects, at
any point of time - both can be locked.
0
 
LVL 2

Author Comment

by:SunScreenCert
ID: 24825318
but what i know that lock1 and lock2 being static acquires lock on the class, so the same class lock cannot be obtained twice even if they are different objects
0
 
LVL 23

Accepted Solution

by:
Ajay-Singh earned 500 total points
ID: 24825423
You have,
   static Object lock1 = new Object();

This means that lock1 object is class-level variable initialized to an
instance of Object. The same is true with lock2. Now, lock1 and lock2
variables are pointing to 2 different objects and hence they can be
locked simultaneously.

If you change your code to,
   static Object lock1 = MyClass.class;
   static Object lock2 = MyClass.class;

or
   static Object lock1 = new Object();
   static Object lock2 = lock1;

You can't lock both object concurrently. Now, they point to same instance.
0
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 
LVL 2

Author Comment

by:SunScreenCert
ID: 24827466
ok great explanation, so now tell me that when lock1 and lock2 acquire lock, they acquire lock on different objects, not on Class object. So they run simultaneously. But  since there are two threads running so can they swap acquiring locks.

Sorry for all the silly questions. I am really not able to understand the flow or output. I even changed things this way to understand each output

public class MyClass extends Thread{
      static Object lock1 = new Object();
      static Object lock2 = new Object();

      static volatile int i1, i2, j1, j2, k1, k2;

      public void run(){
            while(i1 < 1){
                  doIt();
                  check();
            }
      }
      
      void doIt(){
            synchronized(lock1){ System.out.println(Thread.currentThread().getName()); i1++; System.out.println(i1); }
            j1++;
            synchronized(lock2){ System.out.println(Thread.currentThread().getName()); k1++; k2++;  System.out.println(k1); System.out.println(k2); }
            j2++;
            synchronized(lock1){ System.out.println(Thread.currentThread().getName()); i2++; System.out.println(i2); }
      }

      void check(){
            try{
                  Thread.sleep(100);
                  if(i1 != i2) System.out.print("i1 " + i1 + "i2 " + i2);
                  else System.out.print("not i1 " + i1 + "not i2 " + i2);
            }catch(InterruptedException e){}
            
            try{
                  Thread.sleep(100);
                  if(j1 != j2) System.out.print("j1 " + j1 + "j2 " + j2);
                  else System.out.print("not j1 " + j1 + "not j2 " + j2);
            }catch(InterruptedException e){}
                        try{
                  Thread.sleep(100);
                  if(k1 != k2) System.out.print("k1 " + k1 + "k2 " + k2);
                  else System.out.print("not k1 " + k1 + "not k2 " + k2);
            }catch(InterruptedException e){}
            
      }

      public static void main(String... args){
            new Thread(new MyClass(),"First Thread").start();
            //new Thread(new MyClass(), "Second Thread").start();      
      }
}
      
0
 
LVL 2

Author Comment

by:SunScreenCert
ID: 24827668
ok i made this simple program to understand it
import java.util.*;
class MyCurrentDate implements Runnable{
      Date d = new Date();
      public void run(){
            synchronized(MyCurrentDate.class){
      for(int i = 0; i < 2; i++){
            System.out.println(Thread.currentThread() + "  " + d);
            try{
                  Thread.sleep(10000);
            }catch(InterruptedException e){
                  e.printStackTrace();
            }
      }
      }}
      
}
class MyMain{
      public static void main(String... args){
      Thread a = new Thread(new MyCurrentDate(), "a1");
      Thread b = new Thread(new MyCurrentDate(), "b1");
      Thread c = new Thread(new MyCurrentDate(), "c1");
      a.start();
      b.start();
      c.start();
      System.out.println("entering into threadpool");
      }
}



Now since we have class lock once Thread a1 finishes execution it is only after that b1 starts..
and if we synchronize on object that is the this instance then all threads continue running.
0
 
LVL 23

Assisted Solution

by:Ajay-Singh
Ajay-Singh earned 500 total points
ID: 24828837
>> Now since we have class lock once Thread a1 finishes execution it is only after that b1 starts..
and if we synchronize on object that is the this instance then all threads continue running.

Since all the threads here acquire same object (which is reference to class) they will run serially.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why does the Android Studio logcat show this error when the user presses the button? 2 46
more than one jdk and one jre 1 41
login jsp example 24 49
hibernate jars 4 29
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question