假设我的网络应用程序中有一个名为“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
}
如果我这样做,是否可能会遇到同步问题?
最佳答案
工具包的答案是正确的。要解决这个问题,只需将 Foo 的initialise() 方法声明为同步即可。您可以将 Foo 重构为:
private Service service;
public synchronized void initialise() {
if (service == null) {
// load external service
// set field to the loaded service if contacted
}
}
public String get() {
if (service == null) {
initialise(); // try and load the service again
}
// perform operation on the service is service is not null
}
关于Java Web 应用程序同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/227775/