I have a situation where I always need to run a specific bit of code, which depends on the object itself
public abstract class A{ public A(X x){
The problem is as follows. In this example, I use this in the constructor. If another thread tries to access the object through someX.getAList, this may cause the thread to gain access to the object before the constructor finishes work.
You can do this so that the object is added to ALIST using somefunc
public class SomeClass{ private X someX; public A somefunc(boolean b){ A a; if(b){ a = new B(someX); someX.getAList("stuff").add(a); someX.getAList("otherstuff").add(a); }else{ a = new C(someX); someX.getAList("stuff").add(a); someX.getAList("morestuff").add(a); } return a; } }
The problem is that B and C can also be created elsewhere, and that each time B or C is created, they must be added in this way. I do not want to add an object to AList so that it is responsible for the user, but for the class. I also do not want the user to call the init function, which does this for them. On the other hand, I don't need concurrency problems.
Is there a way or template that allows this to be implemented?
Golang has something like defer that allows you to run a piece of code after the function / method / constructor completes.
source share