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 synchronizing a method and synchronizing a block of code in the method

 
Anwar Hussain
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If we synchronize a method and if one thread enters that synchronized method the other threads can't enter the same or other synchronized methods of that class.
Then what about the block of synchronized code.What happens if one thread is executing that block of code.Can the other threads enter the other methods???Please help me come out of this confusion.
 
Sachin Joshi
Ranch Hand
Posts: 83
Java Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is fundamental question about thread synchronization and lock.
You need to understand how locking works when we use synchronized keyword.

Just to answer this question, Other threads can enter other methods of "that object" if those methods are not synchronized.

Here are more similar scenarios you can look at and brainstorm about. Java Threading Questions

Best way to learn threading fundamentals is to start writing simple programs and observe the output.
 
paresh vernekar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would depend on the object instance that you as the lock for the synchronize block within your method.If the same instance is used, then in that case if one thread is executing within that synchronized code then another thread will not be able to execute a synchronized block within another method using the same lock
 
Sachin Joshi
Ranch Hand
Posts: 83
Java Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a good book I would suggest you to refer for better understanding on threading "Thinking in Java" by Bruce Eckel
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Too difficult a question for "beginning Java". Moving.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian Goetz's book is another good reference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic