I have a class which has an internal instance of another class.
@Singleton
class ClassA {
private var classBInstance: ClassB
init{
classBInstance = ClassB()
}
fun performOperation(): Result {
return classBInsatnce.doSomething()
// doSomething() takes about 4 seconds
}
fun updateClassB() {
classBInstance = ClassB()
}
}
ClassA is a singleton is used by multiple threads which call performOperation() on it. Now, if a consumer calls performOperation and thus internally classBInstance.doSomething() is called, and while this is being processed (for 4 seconds), if someone else calls updateClassB(), due to which the variable classBInstance now holds a new instance if ClassB. So what will happen to the earlier consumer, whose operation (doSomething() is still in progress in the previous instance of ClassB.
- Will doSomething() still perform its full operation, using the earlier instance of ClassB? for this consumer. And for any further requests, doSomething of new instance of ClassB is used.
- Or would there be some issue in the doSomething() of the previous ClassB instance, as soon as the variable is replace.
I ask, coz the idea is that I would like to makes sure that when the instance held by classBInstance is updated to new instances, any existing calls being processed by performOperation() are done with older instances of ClassB and only after ClassB new instance is set into classBInstance variable, then only new instance classB is used for any further calls to performOperation()
Could someone please help clarify this? Thanks
I have tried to read about class instances and how they operate but had this confusion about this edge case