I'm understanding synchronization and struck with few doubts after going through different blogs. As per my understanding, Intrinsic lock is acquired by a thread when accessing a synchronized method and other threads need to wait until the first one completes execution giving up the lock for the second thread to execute. But what if both the threads try to access the synchronized blocks from the different object? will that be still called synchronization or not?
class A{
public static synchronized void m1() throws InterruptedException{
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Completed Execution by "+Thread.currentThread().getName());
}
public static void main(String j[]){
new Thread(()->{
try{
new A().m1(); // New object calling m1()
}catch(InterruptedException ie){}
}).start();
new Thread(()->{
try{
new A().m1(); // New object calling m1()
}catch(InterruptedException ie){}
}).start();
}
}
[![Synchronization when separte objects are invoked][1]][1]
Above output When the synchronization is changed to static like
public static synchronized void m1() throws InterruptedException{ //static method
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Completed Execution by "+Thread.currentThread().getName());
}
[![Static Synchronization output][2]][2]
Above output When the static is removed only with synchronized left making it appear as not synchronized from the console output. [1]: https://i.stack.imgur.com/eSKJn.png [2]: https://i.stack.imgur.com/cMx4t.png
So my query is when the method is declared static synchronized and when the different threads calling that method gets the lock from which object ? As when synchronized method is called from different new instances of object need not be called synchronized and the lock is attained on which object in this case?