Hi!
I have to implement Singleton pattern, but I have the following restriction: The getInstance() method should not stop the entire application.
I wrote the following code, to achieve my objective:
public class ServiceProvider {
private static Service service;
private static final PrivateClass singletonProvider = new PrivateClass();
private ServiceProvider() {}
public static synchronized Service getInstance() throws MyException {
if (service == null) {
Thread thread = new Thread(singletonProvider);
thread.start();
try {
// Ten seconds for the construction of the service field.
Thread.sleep(10000);
} catch (InterruptedException ex) {
throw new MyException("InterruptedException!!!", ex);
}
// Is the verification based on Thread.isAlive() safe?
// I am not sure. Please, tell me.
if (!thread.isAlive()) {
if (service == null) {
throw new MyException("Service is still not available");
} else {
return service;
}
} else {
throw new MyException("Service is still not available");
}
} else {
return service;
}
}
// Using a private class I do not need to expose the public run() method.
private static class PrivateClass implements Runnable {
private PrivateClass() {}
private synchronized Service defineInstance() throws MyException {
if (service == null) {
service = new Service();
}
return service;
}
public synchronized void run() {
try {
singletonProvider.defineInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Service {
public Service() throws MyException {
try {
// Simulating a problem: the constructor is taking 20 seconds to be finished.
Thread.sleep(20000);
} catch (InterruptedException ex) {
throw new MyException("InterruptedException in the Service constructor", ex);
}
}
public void method() {
//...
}
}
I am just not sure if the verification based on Thread.isAlive() is safe.
Thanks!!!