Solved

synchronized  method lock

Posted on 2013-01-22
7
305 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
  • 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now