0

Consider the following snippet,

Class A {

public static synchronized void print() {

   //Print something

}

public static void doSomething() {
    //Do Something
}

}

Now is it possible for two threads to access print() and doSomething() concurrently. Does the lock on print() affect doSomething() in this case since the lock on print() is class level locking. Please clarify me !

  • This has nothing to do with static and all to do with two methods being synchronized with the same monitor. – Hovercraft Full Of Eels Aug 30 '17 at 00:56
  • I have made `synchronised` over only the first method. Then how could my second method locked within the monitor.. Please clarify me.. –  Aug 30 '17 at 00:58
  • 1
    Static synchronized method is the same as `synchronized (A.class) {...}`. https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.3.6 – Radiodef Aug 30 '17 at 01:00
  • 1
    The synchronization only affects the method(s) that are synchronized. – Hovercraft Full Of Eels Aug 30 '17 at 01:03
  • If `synchronisation` could affect only the method to which it is applied to then why I couldn't access both method simultaneously (since only one is synchronised and the other one is not). please clarify me... –  Aug 30 '17 at 01:10
  • Yes, they can be called by different threads because the thread accessing `print` would obtain the monitor for the class object and the `doSomething` method does not require obtaining the monitor. – Kamran Aug 30 '17 at 01:13
  • @Kamran : So, say a thread T1 is accessing `print` and it holds the lock over the method as it is said as `synchronised` - at the same time another thread T2 could access `doSomething` and it has nothing to do with the monitor which the thread T1 holds. Am I right ? –  Aug 30 '17 at 01:39
  • 1
    Correct. If, both methods were synchronized, T2 would have to wait until T1 released the monitor when the method `print` returned. – Kamran Aug 30 '17 at 01:43
  • Super thanks ! @kamran –  Aug 30 '17 at 01:53

0 Answers0