Solved

synchronized  method lock

Posted on 2013-01-22
7
313 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 50 total points
ID: 38808690
in other words, it is same as below,

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

Accepted Solution

by:
mccarl earned 300 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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 

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 35

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 35

Expert Comment

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

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Way to decrease size of apk file 9 112
Facing this issue for maven proxy setting 2 27
swing controls 2 24
web project error add remove 1 56
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

696 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