This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to call a synchronized method?  RSS feed

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • 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.
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • 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
  • 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?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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
  • 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 ]
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These two pieces of code are the same


 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!