I read the Wikipeida's Singleton introduction, and wrote this Singleton class. Could there be any thread safety issue?
public class Engine {
private static volatile Engine instance = null;
private final Pipeline pipeline;
private Engine() {
pipeline = createEngine(SystemProperties.LANGUAGE);
}
public static Engine getInstance() {
if (instance == null) {
synchronized (Engine.class) {
if (instance == null) {
instance = new Engine();
}
}
}
return instance;
}
private Pipeline createEngine(Constants.Language langauge) {
Pipeline pipeline;
if (langauge == Constants.Language.Chinese) {
Properties props = IOUtils.readProperties("properties/chinese.properties");
pipeline = new Pipeline(props);
} else if (langauge == Constants.Language.English) {
Properties props = IOUtils.readProperties("properties/english.properties");
pipeline = new Pipeline(props);
} else {
throw new IllegalStateException("Unknow langauge not supported!");
}
return pipeline;
}
}
Client code to use it:
private List<String> segment(String str) {
Engine ENGINE = Engine.getInstance();
List<String> tokens = new ArrayList<>();
...
try {
ENGINE.annotate(tokens);
}catch(Exception e){
log.warn("can't annotate this sentence:" + str);
}
...
return tokens;
}