This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronized block scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronized block scope" Watch "Synchronized block scope" New topic
Author

Synchronized block scope

ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

hi all ,

can anyone tell me the scope of the synchronized block ie whether the synchronized block expands across methods or only inside the method block .
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

If you synchronize a method, then only that method is synchronized. Any other non-synchronized method that this method calls can be called by any other thread on the same object at the same time...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

Ankit Garg wrote:If you synchronize a method, then only that method is synchronized. Any other non-synchronized method that this method calls can be called by any other thread on the same object at the same time...


Ankit, Very good use of word.
ragi, please note that "any other thread on the same object" means the following:



Here t1 and t2 are two different threads on the same object dc.


Java Experience
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281


Hi ragi,

if you use synchronized block then scope of synchronization remains on block boundary e.g.

synchronized (System.in){
//some code

}

though points to remember

1) Java supports re entrant entry , so if a thread calls another synchronized method (which synchronize on same object whose lock calling thread holds) it will go there without waiting because it holds the lock.
2) Thread acquire lock before entering synchronized block/method and releases lock when they leave block (either normal or due to exception).

Thanks
Javin


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
 
 
subject: Synchronized block scope