jeudi 29 janvier 2015

Java singleton with init method

Singleton is a service that require injection of authentication and configuration data. I end with class:



class SingleService {
private String conn;
private String user;
private String pass;

private SingleService() {
// Can throw exception!!
conn = Config.getProperty("conn");
user = Config.getProperty("user");
pass = Config.getProperty("pass");
// Can throw exception!!
internalService = tryConnect(conn, user, pass);
}

private static SingleService instance;

public static void init() {
instance = new SingleService();
}

public static synchronized SingleService getInstance() {
if (instance == null) init();
return instance;
}
}


Dedicated init() method used for exception handling during application startup to early detect initialisation error cause later we just call getInstance() and doesn't expect get error, see:



class App {
public static void main(String args[]) {
try {
Config.init("classpath:auth.properties");
SingleService.init();
} catch (Exception ex) {
logger.error("Can't init SingleService...");
System.exit()
}
doJob();
}
private static void doJob() {
SingleService.getInstance().doJob();
}
}


I worry about init() method and singleton class signature. Fill that class designed badly but don't understand what wrong.


Is it possible to move away initialisation from getSingleton() and synchronized and preserving control on exception during initialisation?


Aucun commentaire:

Enregistrer un commentaire