Issue
I create a hierarchy from an abstract class and two children that are used in class F and pass them to the service
@Getter
abstract class A {
private final B b;
public A(B b) {
this.b = b;
}
abstract void doSomething();
}
@Getter
class B {
private final String someProperty;
}
class C extends A {
public C(B b) {
super(b);
}
@Override
void doSomething() {
super.getb().getSomeProperty();
}
}
class D extends A {
public D(B b) {
super(b);
}
@Override
void doSomething() {
super.getb().getSomeProperty();
}
}
@RestController
class F {
@Autowired
private Service service;
@GetMapping
public void methodOne() {
A a1 = new C(new B("ccc"));
service.make(a1);
}
@GetMapping
public void methodTwo() {
A a1 = new D(new B("ddd"));
service.make(a1);
}
}
@Service
public class Service {
public void make(A a) {
a.doSomething();
}
}
The construction that I described above in case we have a lot of clients who call our API will there be any problems in thread safety with the state of our abstract class or not?
Solution
"Thread Safety" thing comes into the picture when multiple threads are trying to manipulate same object and by allowing to do so may end up with inconsistent state of the Object which is obviously not acceptable for any application.
Your question is about the Object you've declared in your abstract parent class, now as I said earlier the problem will only be there if multiple threads are using the same object, since you're creating new objects every time the service method is getting called, you are safe why?, because the scope of the object is limited to the method and multiple threads can not use the same object as for each method call you'll have a different object.
Now consider this case, in this case thread safety is a concern,
@Service
class UnSafeClass {
private MyClass myClassObject;
public void doSomething() {
myClassObject.changeData();//Same object will be used by multiple threads
}
}
So, your current implementation does not have any thread safety concerns but we should definitely need to clarify on where exactly you need to take care of thread safety.
Answered By - aakash