?
Solved

synchronized  method lock

Posted on 2013-01-22
7
Medium Priority
?
320 Views
Last Modified: 2013-02-12
hi guys

scenario 1
List list = new ArrayList();
public boolean myMethod(E x){
synchronized(list) -- thread acquires a lock which is the 'list'

scenario 2
List list = new ArrayList();
public synchronized boolean myMethod(E x){
// does thread acquire a lock here? what is the name of that lock ?
..
}

thanks
0
Comment
Question by:royjayd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 26

Expert Comment

by:ksivananth
ID: 38808686
>>does thread acquire a lock here? what is the name of that lock ?

yes, it is the object instance of the class where myMethod resides
0
 
LVL 26

Assisted Solution

by:ksivananth
ksivananth earned 200 total points
ID: 38808690
in other words, it is same as below,

public boolean myMethod(E x){
  synchronized( this ){
...
  }
}
0
 
LVL 36

Accepted Solution

by:
mccarl earned 1200 total points
ID: 38808739
does thread acquire a lock here? what is the name of that lock ?
Yes, the lock is acquired on the object of the class that defines your 'myMethod'. You need to expand the above to fully understand.

Object1.java
public class Object1 {
    public boolean myMethodNoSync(String id) {
        System.out.println("myMethodNoSync called - " + id);
        
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
        }
        
        System.out.println("myMethodNoSync returning - " + id);
        return true;
    }
    
    public synchronized boolean mySynchronizedMethod(String id) {
        System.out.println("mySynchronizedMethod called - " + id);
        
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
        }
        
        System.out.println("mySynchronizedMethod returning - " + id);
        return true;
    }
    
    public boolean myMethodWithExplicitSynchronization(String id) {
        synchronized (this) {
            System.out.println("myMethodWithExplicitSynchronization called - " + id);
            
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {
            }
            
            System.out.println("myMethodWithExplicitSynchronization returning - " + id);
            return true;
        }
    }
}

Open in new window

Test.java
public class Test {
    public static void main(String[] args) throws Exception {
        
        // Print '.'s every 200ms so that we can see better when things happen
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 57; i++) {
                    System.out.println(".");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();
        
        
        // Create our object1 which as well as having the functionality is also the *actual* object that is locked
        final Object1 object1 = new Object1();
        
        Thread t1;
        Thread t2;
        
        
        
        
        // Create and start 2 threads that will call 'myMethodNoSync'
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.myMethodNoSync("t1");
            }
        });
        t1.start();
        
        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.myMethodNoSync("t2");
            }
        });
        t2.start();
        
        // Wait for those two threads to finish
        t1.join();
        t2.join();
        
        Thread.sleep(1000);
        
        
        
        
        // Create and start 2 threads that will call 'mySynchronizedMethod'
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.mySynchronizedMethod("t1");
            }
        });
        t1.start();
        
        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.mySynchronizedMethod("t2");
            }
        });
        t2.start();
        
        t1.join();
        t2.join();
        
        Thread.sleep(1000);
        
        
        
        
        // Create and start 2 threads that will call 'myMethodWithExplicitSynchronization'
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.myMethodWithExplicitSynchronization("t1");
            }
        });
        t1.start();
        
        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.myMethodWithExplicitSynchronization("t2");
            }
        });
        t2.start();
        
        t1.join();
        t2.join();
        
        Thread.sleep(1000);
        
        
        
        
        // Create and start 2 threads one will lock on the 'object1' object and the other will call 'mySynchronizedMethod' - NOTE they still run separately proving that 'object1' is the lock
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object1) {
                    System.out.println("synchronized on object1 block starts - t1");
                    
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ex) {
                    }
                    
                    System.out.println("synchronized on object1 block ends - t1");
                }
            }
        });
        t1.start();
        
        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                object1.mySynchronizedMethod("t2");
            }
        });
        t2.start();
        
        t1.join();
        t2.join();
        
        Thread.sleep(1000);
    }
}

Open in new window

The above code shows the 4 different situations, they should make it fairly self explanatory. Ask questions if that isn't the case.
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 

Author Comment

by:royjayd
ID: 38861414
hi mccarl

thanks for the detailed code
>>>// Create and start 2 threads one will lock on the 'object1' object and the other will call 'mySynchronizedMethod' - NOTE they still run separately proving that 'object1' is the lock

I couldnt understand what you meant by above statement.
they will run seperately anywhich ways since they are two seperate threads, t1 and t2 , right ?
0
 
LVL 36

Expert Comment

by:mccarl
ID: 38862005
Sorry bad choice of words... I should have said sequentially rather than separately.

So what I trying to point out is that both the "synchronized(object1)" statement and the calling of "object1.mySynchronizedMethod" will both use object1 as the lock, so as the output shows, one will start and finish running before the other can start, ie. they run sequentially and not at the same time.

Does that make it clear?
0
 

Author Comment

by:royjayd
ID: 38879839
great.
0
 
LVL 36

Expert Comment

by:mccarl
ID: 38882631
I'm glad that it helped!
0

Featured Post

Independent Software Vendors: 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!

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…
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 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…
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:
Suggested Courses
Course of the Month12 days, 11 hours left to enroll

777 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