user3663882
user3663882

Reputation: 7367

Understanding synchronized methods

I'm new to concurrency and would like to ask the following question. I have the following class:

public class MyClass{

    public synchronized void method1(){
         //do some
    }

    public synchronized void method2(){
         //do another some
    }
}

So, as far as understand when some thread start executing one of those methods it acquires a lock on this. My question is if it means that any other thread cannot execute any method of the same object unless the thread release this and what should I do if want to permit the concurrent invocation?

Upvotes: 2

Views: 105

Answers (2)

Kaushik Lele
Kaushik Lele

Reputation: 6637

@user3663882, as replied above by @Hoopje "no other thread can execute any synchronized method of the same object."

You further asked. "But what if need to make this restriction a littler weaker. I want allow two different threads invoke the two different method of the same object. Does it make a sense?" In this case you need to redesign your methods. Instead of making whole method as synchronized you can mark only specific code of each method as synchronized. Thus locking period will be minimized.

public class MyClass{

public void method1(){
     //do some before synchronization 
     synchronized(this){
         // do some
     }
     //do some before synchronization 
}

public void method2(){
     //do some before synchronization 
     synchronized(this){
         // do some
     }
     //do some before synchronization 
}
}

Upvotes: 2

Hoopje
Hoopje

Reputation: 12942

It means that no other thread can execute any synchronized method of the same object. If a method is not synchronized, it does not try to obtain a lock, so it can be called by different threads concurrently. (Of course, then you have to make sure yourself that the method is thread-safe.)

If you want more control over the synchronization strategy, you will need to create and maintain your own locks. The classic way to that is something like the following:

class {
    Object lock1;
    Object lock2;
    void method1() {
        synchronized (lock1) {
            ...
        }
    }
    void method2() {
        synchronized (lock2) {
            ...
        }
    }
}

This uses the fact that each Java object comes with a built-in lock. Now the two methods use their own lock, so when method1 is locked by a thread, a different thread can still call method2.

For even more control how many threads can read from or write to your objects, you can use locks from the java.util.concurrent.locks package.

Upvotes: 5

Related Questions