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


walid aly
Ranch Hand

Joined: Nov 06, 2002
Posts: 38
can any one plz help me what is the meaning of synchronizing on an object

thanks alot
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
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.

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Cory Wilkerson
Ranch Hand

Joined: Aug 14, 2001
Posts: 84
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.
[ January 06, 2003: Message edited by: Cory Wilkerson ]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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:


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.

"I'm not back." - Bill Harding, Twister
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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
I agree. Here's the link:
subject: synchronized(obj)
jQuery in Action, 3rd edition