Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized(obj)

 
walid aly
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any one plz help me what is the meaning of synchronizing on an object
synchronized(obj)

and
synchronized(this)
thanks alot
walid
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization comes in two flavors. You can synchronize an entire method or you can synchronize access to a shared object for a block scope.
synchronized(obj) means the access to obj is exclusive to the thread that executes the following block and all other threads must wait till the current thread completes executing the block.
sychronized(this) means the same, but the shared object is the current instance ie., the object that owns the code being executed.
Hope that helps.
 
Cory Wilkerson
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the same note....consider the following:

Even though lock has nothing to do with what's occuring...will the block of code be effectively locked to the executing thread?
Seems a bit odd to me that I could lock on "lock" and expect the following block to be thread safe though it has no relation to lock.
If anyone could offer insight, I would be most happy.
Thanks,
Cory
[ January 06, 2003: Message edited by: Cory Wilkerson ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But lock is linked to the class the code is in. It's a private class variable; there is exactly one lock object associated with the class , and the only way to get to that lock is by going through the class. So any thread trying to run the incrementCounter() method will have to compete for a lock on the single lock object. The net effect is virtually identical to this:

or

There's really no point to creating a separate lock object here - it just serves to confuse people. Though it may be useful for teaching purposes, or as a prelude to more complex thread locking patterns.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although Jim already sort of said it, it's worth stating explicitly thatIs functionally equivalent toFrom this point of view, this whole "synchronized method" business is just a bit of syntactic sugar. If you understand synchronized blocks, you also understand synchronized methods, and vice versa.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic