Can two threads call two different synchronized instance methods of an Object?

Upasana | December 16, 2017 | 1 min read | 322 views


No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods.

public class Common {
  public synchronized void synchronizedMethod1() {
   System.out.println("synchronizedMethod1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("synchronizedMethod1 done");
  }

  public synchronized void synchronizedMethod2() {
   System.out.println("synchronizedMethod1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
 }

Top articles in this category:
  1. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  2. can we write a java method that swaps two integers
  3. What are four principles of OOP, How aggregation is different than Composition?
  4. What is difference between Vector and ArrayList, which one shall be preferred
  5. Difference between Callable and Runnable Interface
  6. ThreadLocal with examples in Java
  7. What is difference between sleep() and wait() method in Java?

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.