This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Difference between synchronized method and block and advantages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Difference between synchronized method and block and advantages" Watch "Difference between synchronized method and block and advantages" New topic
Author

Difference between synchronized method and block and advantages

veena bijur
Ranch Hand

Joined: May 16, 2011
Posts: 67
Synchronized Method :
Only 1 user can use that method at any given point of time. i.e., all requests will be queued and are executed.

Synchronized block :
Statements in the block are executed sequentially. eg - while working with GUI, if you display any dialog window, execution proceeds without waiting for user input (like ok or cacel). If the show() call and next steps are in synchronized block, execution is paused until user enters input this is the advantage.


Is the above difference and uses correct?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

veena bijur wrote:Synchronized Method :
Only 1 user can use that method at any given point of time. i.e., all requests will be queued and are executed.


False. Synchronization has nothing to do with users. And multiple threads can still execute a synced block or method simultaneously, if they're all syncing on different locks.

A synchronized method is just syntactic sugar for a synchronized block. Functionally, they're identical.




In terms of mutual exclusiong, the ONLY things that synchronized does are: 1) Wait until the indicated lock is not held by another thread, and 2) Obtain the indicated lock. That's all. And that's what every use of the synchronized keyword does. The only difference between a synced method and a synced block is that in the case of the method, which lock you obtain is determined by the context.

There is one very small difference in how they're implemented that makes a synchronized method execute 1 or 2 fewer bytecodes than a syncrhonized block. Or at least there was many years ago. I don't know if it's still part of the spec. That's not worth worrying about though, and functionally, they're identical.
veena bijur
Ranch Hand

Joined: May 16, 2011
Posts: 67


OK. Thanks for the reply.
 
Consider Paul's rocket mass heater.
 
subject: Difference between synchronized method and block and advantages
 
Similar Threads
static synchronized block
confusion about object lock.
Threads
Synchronized Block and Synchronized method
Please explain this sentence