This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Difference between synchronized method and block and advantages

 
veena bijur
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


OK. Thanks for the reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic