Solved

Plz explain this program..

Posted on 2009-07-10
6
198 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
javap bin 2 41
difference of if loops 23 62
ejb wildfly example 2 28
servlet and mdb, jms error 1 39
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

821 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