It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Synchronized Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Synchronized Methods" Watch "Static Synchronized Methods" New topic

Static Synchronized Methods

Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
If the following method existed:
class MyClass {
synchronized void insync() {}
void notsynchronized() {}
static synchronized void staticsynctest {}
What would happen if staticsynctest were called?
Would I have access to insync, or notsynchronized?
Would I have access to static class data or class data?
Would I have access to instance data?

mousami bhattacharya
Ranch Hand

Joined: May 13, 2001
Posts: 40
Each object has a lock(monitor) ,and each class also has a lock(monitor),the lock on objects is completely independent of the class lock and vice-versa.
So if you call a synchronized static method ,then that thread gets the lock of the class ,but other thread can call instance methods(synchronized ot others)
Hope this helps
jeena jose
Ranch Hand

Joined: May 06, 2001
Posts: 69
what about the access to class variable(static) when static synchronized method is called???
access to instance variable when synchronized instance metod is called ???
Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
It is important to remeber that Static methods are run on the class, not the instance. It woun't have any reference to the instance, unless you take extra messures to make sure that the method has it (like sending it as a parameter, or seting a static variable to point to it). Thus you wont be able to access anything that is assosiated with th instans, i.e. everything not static in the class. There is no 'this' in static methods.
So to answer your initial questions:
No access to insync() or notsynchronized().
Only static class data.
No instance data.

Though, if you wanted free access to the class, you could change the method to:

and call it with for example staticsynctest(this);
Was that the answer you where looking for?
Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
Hello, thanks for the answers. There is another point I am sure not clear on. When a static synchronized method is called, I understand that the static methods will be locked.
What happens to a static class variable? Would it also be locked?
The thing I am confused on is non-static variables put a lock on the object. In static synchronized methods there is no instance object to lock. What exactly is the lock on?

I agree. Here's the link:
subject: Static Synchronized Methods
It's not a secret anymore!