I would appreciate some opinion on whether the code below is fully thread safe and does not leak the "this" reference? What I'm trying to do is essentially bootstrapping/initialising another service in a background thread using an ExecutorService.
I am just slightly concerned as I've read from somewhere that it is bad practise to start a thread from the constructor as it would leak the "this" reference before the class is fully constructed.
public class MyService {
private final ExecutorService executorService;
private volatile AnotherService anotherService;
private volatile boolean isReady = false;
public MyService(final ExecutorService executorService) {
this.executorService = executorService;
start();
}
private void start() {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
anotherService = init();
isReady = true;
} catch (Exception e) {
// do nothing, just retry later
}
}
});
}
private AnotherService init() {
// some code to initialize
return AnotherServiceBootstrap.getInstance().bootstrap();
}
// some other methods in class
}
Many thanks in advance!