1

Is synchronized keyword in methods prevents running concurrently or calling concurrently by multiple threads in one instance?

We have one object and some synchronized methods and different threads.

I read that synchronized methods prevents multiple threads calling synchronized methods on one object, But How different threads can running synchronized methods concurrently?

Thanks.

1
  • If a synched object/body is entered by a thread, it is locked for other threads. When first thread finishes, it is unlocked and one of others can go in. Feb 19, 2014 at 10:28

2 Answers 2

3

We have one one object and some synchronized methods and different threads.

Synchronization on methods will use the current instance (this) as the lock, so, if there is only on object, multiple thread can't run those methods concurrently.

Is synchronized keyword in methods prevents running concurrently or calling concurrently by multiple threads in one instance?

Prevents running concurrently by multiple threads.

But How different threads can running synchronized methods concurrently?

No, They can't run concurrently.

4
  • So, is there any other possibility of synchronized methods runs concurrently?
    – Sunrise
    Feb 19, 2014 at 10:34
  • @Sunrise : Nope, They can't run concurrently. Feb 19, 2014 at 10:36
  • So, what about if we have multiple object of class?
    – Sunrise
    Feb 19, 2014 at 10:40
  • @Sunrise : It's depends on, like, if one group of threads lock on one object, then, in that group, they can't run concurrently. Feb 19, 2014 at 10:42
1

If you have a class that looks like this,

class C {
    public synchronized void method1() { ... }
    public synchronized void method2() { ... }
}

You can't have any two threads running method1, or method2, or any combination of the two concurrently.

When using synchronized methods, you're declaring that at most one thread may be running one of the synchronized methods, in any given instant.

If there are methods you would like to run concurrently, you'll probably need to look into managing multiple locks (synchronized blocks, instead of methods, using some monitor other than this).

Maybe you should start with this lesson.

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.