Solved

Plz explain this program..

Posted on 2009-07-10
6
194 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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now