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 -----
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With