Question about Java Synchronization

Hi there,

I have a question about "lock" in synchronization. Basically, I am not sure why I need to make a static lock object.

To illustrate, pls refer to the following two programs. The program is suppose to print "3" (the value of "final"). The first one will print out "1". I know it is because the 1st one uses a lock object which is not static and the 2nd uses a static lock object. But why?

I would appreciate it very much if you could explain in details (just a litttle bit) about Synchronization and lock (why/when static)

Thanks.

public class WrongCriticalSection  extends Thread {
      
      private static final int SLEEP_UNITS = 300;

      private static int shared = 0;
      
      private Object lock = null;
      
      public WrongCriticalSection(){
            lock = new Integer(0);
      }
      

      public void run() {
            int local;
            
            synchronized ( lock ) {      
                  local = shared;
                  try {
                        sleep(SLEEP_UNITS);   // perform lenghty computations
                  }
                  catch (InterruptedException e){}
            
                  local = local + 1;
                  shared = local;
            }
      }
      

      public static void main(String[] args) {

            Thread th1 = new WrongCriticalSection();
            Thread th2 = new WrongCriticalSection();
            Thread th3 = new WrongCriticalSection();
            
            th1.start();
            th2.start();
            th3.start();
            
            try {
                  th1.join();
                  th2.join();
                  th3.join();
            }
            catch (InterruptedException e){}
            
            System.out.println("Shared is: " + shared);
      }
}

and

public class CriticalSection extends Thread {
      
      private static final int SLEEP_UNITS = 300;

      private static int shared = 0;
      
      private static Object lock = new Integer(0);  // any object is fine
      
      public void run() {
            int local;
            
            synchronized ( lock ) {      
                  local = shared;
                  try {
                        sleep(SLEEP_UNITS);   // perform lenghty computations
                  }
                  catch (InterruptedException e){}
            
                  local = local + 1;
                  shared = local;
            }
      }
      

      public static void main(String[] args) {

            Thread th1 = new CriticalSection();
            Thread th2 = new CriticalSection();
            Thread th3 = new CriticalSection();
            
            th1.start();
            th2.start();
            th3.start();
            
            try {
                  th1.join();
                  th2.join();
                  th3.join();
            }
            catch (InterruptedException e){}
            
            System.out.println("Shared is: " + shared);
      }
}
LVL 1
tiger0516Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mick BarryJava DeveloperCommented:
In the first class each thread is locking on different objects because each instance has its own set of member variables.

In the second class each thread locks on the *same* object because class (static) variables are shared by all instances of that class.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tiger0516Author Commented:
What is I say

private int shared = 0;

instead of

private static int shared = 0;

What shall I do to get the same result?

Thanks.

Feel confused by thread :(
tiger0516Author Commented:
>What is I say

Shall be What if I say
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Tommy BraasCommented:
The class WrongCriticalSection has a lock per instance of that class. That means that there is NO synchronization between threads.

The  class CriticalSection has one lock for the class. That means that all instances of this class shares the same lock, i.e. you achieve synchronization between threads in the critical section.
Mayank SAssociate Director - Product EngineeringCommented:
>> Basically, I am not sure why I need to make a static lock object.

I assume it is a continuation of your old question: >> http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21815874.html

You should've asked for clarification there instead of opening a new one :) Anyway, the reason for having it static is that all objects should share it. So if one object locks it, the other objects will not be able to enter that block of code which has acquired the lock. They will wait for the current object to finish execution, then they will acquire a lock and enter it.
Tommy BraasCommented:
;-D
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.