| Author |
Difference between synchronizing a method and synchronizing a block of code in the method
|
Anwar Hussain
Ranch Hand
Joined: Jul 24, 2009
Posts: 35
|
|
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
Joined: Aug 06, 2008
Posts: 83
|
|
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.
|
Web Development Tips and Tutorials - By Sachin
|
 |
paresh vernekar
Ranch Hand
Joined: Jul 10, 2006
Posts: 52
|
|
|
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
Joined: Aug 06, 2008
Posts: 83
|
|
|
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
Joined: Oct 13, 2005
Posts: 32830
|
|
|
Too difficult a question for "beginning Java". Moving.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
|
Brian Goetz's book is another good reference.
|
 |
 |
|
|
subject: Difference between synchronizing a method and synchronizing a block of code in the method
|
|
|