• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static and non-static synchronized methods

 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can a synchronized non-static method call synchronized static method and vice-versa.
 
Mo Jay
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has nothing to do with wether the methods are synchronized or not, this has something to do with static method calling non-static method and vice versa.
Answer is NO, static methods cannot call non-static methods directly. You can instantiate the class and use the object reference to make the call. By the way there a tricky way that you can get away with the syntax but it is not considered good coding style.

Cheers!!!
 
Eduardo Bueno
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Non-static methods are allowed to call static methods.
 
Mo Jay
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are totally right Eduardo.

Cheers!!!
 
Michael Angstadt
Ranch Hand
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like others have said, a static method cannot call a non-static method, whether it's synchronized or not. That's simple.

But it is possible for a non-static synchronized method to call a static synchronized method. However, the thread that's calling the static method may need to wait for the static method's lock to be released.

Static synchronized methods use the class's Class object as a lock. So the follow two methods are equivalent:

Non-static synchronized methods use the current object instance as a lock. So these two methods are equivalent:
 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually i meant to ask something different . Let me rephrase my question. Suppose a thread1 in non-static synchronized block,after acquiring object lock, calls a static synhronized method, then will thread1 acquire class lock or not, since a instance method can always call static method?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naresh Chaurasia wrote:Suppose a thread1 in non-static synchronized block,after acquiring object lock, calls a static synhronized method, then will thread1 acquire class lock or not


Only if another thread hasn't aquired the class lock at that time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic