posted 16 years ago
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.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi