This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Synchronization block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Synchronization block" Watch "Synchronization block" New topic

Synchronization block

Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105

could anyone please tell me the difference between having a synchronized block on current object like synchronized(this) or having a synchronization block on arbitrary object, because the following programme is executing the println method randomly based on calling by two threads on two different object in run method.

How can I differentiate then?
Roland Maurer

Joined: Nov 23, 2008
Posts: 17
If you sync(this) in method A and B -> A can not be accessed while somebody is in B or vice versa .
If you sync A with sync(AObj) and B with(BObj) A can be accessed while somebody is in B.

take a look to :
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231

Above you are synchronizing on the lock of the object *out* in class System which is a static member variable i.e. only one copy of *out* exists at the class level and thus only *one* lock for that object. Since you have a single lock which your two threads *d* and *d1* are trying to acquire hence whichever thread gets scheduled by the scheduler will acquire that lock to the mutual exclusion of the other thread.

Had you used synchronized(this) then both your threads would be acquiring two different locks i.e. lock on the currently executing thread object referred by *this*. Hence there would be no problem for both the threads to execute simultaneously(if two or more CPU system).

Now you can start two or more threads, but you cannot guarantee the order in which the thread scheduler is going to pick up and schedule those threads in order to be run. You can try to influence the thread scheduler by using Thread priorities but still you cannot guarantee the execution order of the threads.

I hope i am making sense to you.

I agree. Here's the link:
subject: Synchronization block
It's not a secret anymore!