1

假设我的网络应用程序中有一个名为“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
}

如果我做这样的事情,我可能会遇到同步问题吗?

4

2 回答 2

1

toolkit的答案是正确的。要解决这个问题,只需声明你的 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
}
于 2008-10-22T23:56:08.453 回答
0

是的,您将遇到同步问题。

假设您有一个 servlet:

public class FooServlet extends HttpServlet {

    private MyBean myBean;

    public void init() {
        myBean = (MyBean) WebApplicationContextUtils.
            getRequiredWebApplicationContext(getServletContext()).getBean("myBean");
    }

    public void doGet(HttpRequest request, HttpResponse response) {
        String string = myBean.get();
        ....
    }

}

class MyBean {
    public String get() {
        if (service == null) {
            // try and load the service again
        }
        // perform operation on the service is service is not null
    }
}

您的 bean 定义如下所示:

<bean id="myBean" class="com.foo.MyBean" init-method="initialise" />

问题是您的 servlet 实例被多个请求线程使用。因此,由 service == null 保护的代码块可能被多个线程输入。

最好的解决方法(避免双重检查锁定等)是:

class MyBean {
    public synchronized String get() {
        if (service == null) {
            // try and load the service again
        }
        // perform operation on the service is service is not null
    }
}

希望这是有道理的。如果没有,请发表评论。

于 2008-10-22T22:45:28.830 回答