Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Question about Java Synchronization

Posted on 2006-04-18
6
Medium Priority
?
230 Views
Last Modified: 2010-03-31
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);
      }
}
0
Comment
Question by:tiger0516
6 Comments
 
LVL 92

Accepted Solution

by:
objects earned 800 total points
ID: 16483599
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.
0
 
LVL 1

Author Comment

by:tiger0516
ID: 16483711
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 :(
0
 
LVL 1

Author Comment

by:tiger0516
ID: 16483720
>What is I say

Shall be What if I say
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Assisted Solution

by:Tommy Braas
Tommy Braas earned 600 total points
ID: 16483915
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.
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 600 total points
ID: 16484890
>> 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.
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 16485268
;-D
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month20 days, 17 hours left to enroll

810 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