Note that there are some explanatory texts on larger screens.

plurals
  1. POsynchronized blocks for static and non-static methods
    primarykey
    data
    text
    <p>I created two threads and using a single instance of class called the static and non-static methods of that object. Ideally static methods need to be called using the class name and i did that too. </p> <p>I synchronized both the static and non-static methods on a private static member of the class whose methods the threads are calling. I noticed that the output was synchronized!</p> <p>My questions are:</p> <ol> <li><p>Static methods if synchronized using a synchronized block it usually requires the class instance, then how did it accept a static object! </p></li> <li><p>How was the output synchronized as threads calling static methods acquire the class level lock and threads calling non-static methods acquire object level lock!<br> Even though i have used synchronized block in both the static and non-static methods based on an object, it really shouldn't synchronize; or is it special case with synchronized blocks on static objects?</p></li> </ol> <p>Please let me know.</p> <p>Following is the code i have written:</p> <pre><code>public class StaticNonStaticSynch { public static void main(String[] args) { final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest(); Runnable runnable1 = new Runnable() { @Override public void run() { staticNonStaticTest.nonStaticMethod(); } }; Runnable runnable2 = new Runnable() { @Override public void run() { staticNonStaticTest.staticMethod(); } }; Thread thread1 = new Thread(runnable1, "First Thread"); Thread thread2 = new Thread(runnable2, "Second Thread"); thread1.start(); thread2.start(); } } class StaticNonStaticTest { private static Object object = new Object(); void nonStaticMethod() { synchronized (object) { for(int i=0;i&lt;500;i++) { System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i); } } } static void staticMethod() { synchronized (object) { for(int i=0;i&lt;500;i++) { System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload