假设我的网络应用程序中有一个名为“Foo”类的类。它有一个 initialise() 方法,当使用 Spring 创建 bean 时会调用该方法。然后,initialise() 方法尝试加载外部服务并将其分配给一个字段。如果无法联系到服务,则该字段将设置为空。
private Service service;
public void initialise() {
// load external service
// set field to the loaded service if contacted
// set to field to null if service could not be contacted
}
当有人在类“Foo”上调用 get() 方法时,如果它是在 initialise() 方法中启动的,则将调用该服务。如果服务的字段为空,我想尝试加载外部服务。
public String get() {
if (service == null) {
// try and load the service again
}
// perform operation on the service is service is not null
}
如果我做这样的事情,我可能会遇到同步问题吗?