[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

synchronized  method lock

Posted on 2013-01-22
7
Medium Priority
?
322 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
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!

 

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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

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…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

656 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