The Java Tutorials say: "it is not possible for two invocations of synchronized methods on the same object to interleave."
What does this mean for a static method
? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?
For those who are not familiar static synchronized method locked on class object e.g. for string class its String.class while instance synchronized method locks on current instance of Object denoted by “this” keyword in Java. Since both of these object are different they have different lock so while one thread is executing static synchronized method , other thread in java doesn’t need to wait for that thread to return instead it will acquire separate lock denoted byte .class literal and enter into static synchronized method.
Unless you implement g() as follows:
I find this pattern useful also when I want to implement mutual exclusion between different instances of the object (which is needed when accesing an external resource, for example).