Sign in to follow this  

static method stalls?

This topic is 4108 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, does anyone know if the following code would stall in Java with multithreading? :
class MyObject {
  public void testStall() {
    MyStaticClass.myFunction(this);
  }
}

static class MyStaticClass {
  static public void myFunction(MyObject obj) {
    //do something with obj
  }
}

Ok, now it would be used like this: Thread 1:
loop {
  myObject.testStall();
}
Thread 2:
loop {
  myObject.testStall();
}
So, will this stall or is it perfectly safe? Thank you!

Share this post


Link to post
Share on other sites
A static function is no different from a regular function in the sense of multithreaded programming. A non-static method forces you go through an instance of the object, whereas a static method allows you to go through an instance of the object or the class name of the object.

So, depending on your myFunction body, you may or may not need to worry about stalling. Does myFunction deal with member variables of the class? Does it call other functions? Does it have static variables? If so, then yes, you need to worry about synchronization (i.e. wrap w/ mutex). I don't know exactly what 'do something with obj' entails, so I can't give an exact answer. The answer would be the same, though, if you removed static from the method declaration.

Adding the static qualifier to the class name means the class cannot be instantiated. There will only exist one copy. Again, this doesn't affect it's methods (as stated above), but it will force you to synchronize acessing member data of the static class (as only one copy of data exists, so all threads will be accessing the same data).

Share this post


Link to post
Share on other sites

This topic is 4108 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this