Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety, static methods and some weird code

I recently stumbled upon piece of code similar to the one below. This code does reek right off. Looks like singleton but its not because there is no private constructor. I know for sure this is going to have thread safety issue given big enough load to it. Specially given class instance. Can someone please point out thread safety issues with this code?

public class AClass extends AnotherClass {

  public static final AClass instance = new AClass();

  public static SomeObject doSomethingThatCallsAService(Params params) {
       return methodThatCallsService(params, instance);
  }

  public static SomeObject methodThatCallsService(Params params, AClass instance) {
      -----call service here ---------
      instance.doSomethingElse();
  }

  private void doSomethingElse() {
      --- do some trivial work -----
  }
}
like image 573
ringadingding Avatar asked Aug 10 '26 19:08

ringadingding


1 Answers

Given that the object does not carry state, there's no concern for thread safety, regardless of the number of threads calling methods on or having a reference to the singleton object.

All the methods in the class, including static ones, don't use any shared data. So whether they call methods on the singleton object or they pass the instance around, there's no need for access to anything to be synchronized.

As the code is, the only data that could possibly need synchronization is params in the argument to methodThatCallsService, and that's only if this method modifies the data and multiple threads hold a reference to the same Params object.

But as far as this class is concerned, it's thread-safe, even if the singleton implementation is vulnerable.

like image 186
ernest_k Avatar answered Aug 13 '26 11:08

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!