| Author |
static and non-static synchronized methods
|
Naresh Chaurasia
Ranch Hand
Joined: May 18, 2005
Posts: 309
|
|
|
Can a synchronized non-static method call synchronized static method and vice-versa.
|
SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
|
 |
Mo Jay
Ranch Hand
Joined: Feb 16, 2009
Posts: 83
|
|
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
Joined: Jun 04, 2009
Posts: 154
|
|
|
Non-static methods are allowed to call static methods.
|
 |
Mo Jay
Ranch Hand
Joined: Feb 16, 2009
Posts: 83
|
|
You are totally right Eduardo.
Cheers!!!
|
 |
Michael Angstadt
Ranch Hand
Joined: Jun 17, 2009
Posts: 272
|
|
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:
|
SCJP 6 || SCWCD 5
|
 |
Naresh Chaurasia
Ranch Hand
Joined: May 18, 2005
Posts: 309
|
|
|
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
Joined: Mar 24, 2008
Posts: 3670
|
|
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.
|
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
|
 |
 |
|
|
subject: static and non-static synchronized methods
|
|
|