File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Synchronized blocks vs methods. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Synchronized blocks vs methods." Watch "Synchronized blocks vs methods." New topic

Synchronized blocks vs methods.

Paul Roubekas

Joined: Jul 17, 2001
Posts: 26
In the following code synchronized is used in a way I do not understand. What is "synchronized" the Objects "lock1" and "lock2" or the code inside the {}?

[This message has been edited by Cindy Glass (edited September 25, 2001).]
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The code inside the {} is "synchronized" using the locks on two arbitrary objects "lock1" and "lock2". The objects are not synchronized.
In most cases that you've probably seen the lock being used is implicit -- it is the object's who owns the synchronized method.
Sun Certified Programmer for the Java� 2 Platform
Bill Hause

Joined: Jan 17, 2001
Posts: 13
The code inside the {} is what is synchronized.
No thread can execute the code in the {} unless it has the "one and only" lock on the "mutex" objects "lock1" or "lock2".
lock1 and lock2 simply serve as objects to lock onto. Note they are static so there is only one instance of each across all instances of TestClass.

---------------------<BR>William D. Hause<BR>
Paul Roubekas

Joined: Jul 17, 2001
Posts: 26
That's right, duh! you can only synch. on one class at a time even if more then one method is synch'ed in the class. So all synch'ed blocks of code must piggieback onto some class.
That clears it up for me, thanks a bunch!
I agree. Here's the link:
subject: Synchronized blocks vs methods.
jQuery in Action, 3rd edition