• 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

how to call a synchronized method?

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,

While calling a synchronized method is it necessary that the calling thread should hold the lock of the object through which it is called?

Regards,
Ajay.
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When thread is calling a synchronized method, then thread must first get

the lock of the object whose synchronized method thread is going to access.
 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok thats fine.

but consider the following example


and it gives the output as

This is in method
This is in method 2

In this case i am not obtaining any lock on the object. how it works?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How would you obtain a lock if you wanted one?

Seriously, look it up and answer.
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When a thread enters in a synchronized method or in a synchronized block, then automatically it acquires first lock.

In your code, when mthd2() is called which is synchronized then automatically thread which is processing mthd1() will acquire the lock of that object which is referred by test.


Naseem
[ June 15, 2006: Message edited by: Naseem Khan ]
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
These two pieces of code are the same


reply
    Bookmark Topic Watch Topic
  • New Topic