• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Synchronized block scope

 
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 .
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...
 
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 300
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
reply
    Bookmark Topic Watch Topic
  • New Topic