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?
One point you have to be careful about (several programmers generally fall in that trap) is that there is no link between synchronized static methods and sync'ed non static methods, ie:
Main:
Thread 1:
Thread 2:
f() and g() are not synchronized with each other and thus can execute totally concurrently.
Have a look at oracle documentation page on Intrinsic Locks and Synchronization
A static method also has an associated object. It belongs to Class.class file in JDK toolkit. When the .class file load into the ram, the Class.class creates a instance of it called template object.
Eg :- when you try to create object from existing customer class like
The Customer.class load into RAM. In that moment Class.class in JDK toolkit creates an Object called Template object and load that Customer.class into that template object.Static members of that Customer.class become attributes and methods in that template object.
So a static method or attribute also has an object
Yes. :)
Below examples gives more clarity between class and object lock, hope below example will help others as well :)
For example we have below methods one acquire class and other acquire object lock :
So, now we can have following scenarios :
When threads using same Object tries to access
objLock
ORstaticLock
method same time (i.e. both threads are trying to access same method)When threads using same Object tries to access
staticLock
andobjLock
methods same time (tries accessing different methods)When threads using different Object tries to access
staticLock
methodWhen threads using different Object tries to access
objLock
methodJust to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is 8.4.3.6, 'synchronized Methods':