Forums Register Login
synchronized methods
there are two synchronized methods,s1 and s2 in the same class and two threads t1 and t2 in the same class.now t1 is inside method s1 and t2 wants to execute s2.Will it be able to able to execute s2.
One more thing,is there one lock per class or one lock per method for our case?
Assuming something like this:

If thread T1 is executing the method m1, then thread T2 will wait when it tries to execute m2 until T1 exits m1. The lock is specific to the instance of the class, i.e. synchronized(this).
Locks go with objects.

For non-static synchronized methods, we lock on the object instance.

For static synchronized methods, we lock on the Class object, so it acts like there is one lock for the whole class.

When we do synchronized(thing) we specify the object.

Imagine an office with only a refrigerator that must be locked to keep riffraff from stealing food. And there is only one key, which is kept on a hook. When you want your lunch, you go to the hook. If the key is there, you take it and go. If not, you wait for somebody else to bring it back.

If I have two offices on neighboring floors that share a refrigerator and a key, that sounds like a static variable. One key for the "class" office. If we have two offices and each has its own refrigerator, that sounds like a member variable, one key per office instance.

Analogies like this always break down at some point. Was it helpful at all? See if it holds up when you get to studying wait, notify and so on.
thanks a lot for your nice explanation

This thread has been viewed 559 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 25, 2018 03:15:21.