On 26/01/15 15:55, Eric Sosman wrote:
On 1/26/2015 10:40 AM, John wrote:
I am amazed at what I saw:
synchronized private void print()
{
System.out.println("printing A");
System.out.println("printing B");
System.out.println("printing C");
}
[... he gets interleaved output ...]
Each Java object has its own lock ("monitor"), independent of the
locks belonging to other Java objects. When you call a synchronized
instance method, Java acquires the lock of the "this" object before
proceeding, and releases it when the method finishes. If there are
several object instances floating around, there are several "this"
and several independent locks.
I thought the method is atomic.
No. Synchronization is not about methods (or code blocks), but
about objects: You lock the *object*, not a method.
Are you sure?
If you have a class with two methods and one (or more) of them is
synchronized and one (or more) isn't then a thread can obtain the lock
on an instance of that class which locks out all other threads from the
synchronized methods but the non synchronized methods of that instance
are still available to other threads.
At least that's how I remember it.
I think that is what Eric is saying.
"you lock *on* an object".