• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

synchronized method lock

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
royjayd
Asked:
royjayd
  • 3
  • 2
  • 2
2 Solutions
 
ksivananthCommented:
>>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
 
ksivananthCommented:
in other words, it is same as below,

public boolean myMethod(E x){
  synchronized( this ){
...
  }
}
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
royjaydAuthor Commented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
royjaydAuthor Commented:
great.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I'm glad that it helped!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now