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).
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 ]
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.
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