Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization block

 
Pawan Arora
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :
http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html

http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic