2008-10-22 131 views
1

假设我在我的Web应用程序中有一个名为class“Foo”的类。它有一个initialise()方法,当使用Spring创建bean时会调用它。 initialise()方法然后尝试加载外部服务并将其分配给一个字段。如果服务无法联系,则该字段将设置为空。Java Web应用程序同步问题

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 
} 

当有人调用get()方法的类“富”,如果它是在INITIALISE()方法启动该服务将被调用。如果服务的字段为空,我想尝试加载外部服务。

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

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

回答

1

工具包的回答是正确的。为了解决这个问题,只需声明你的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 
} 
+0

谢谢!重构的好主意;) – digiarnie 2008-10-22 23:57:55

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实例被多个线程的请求。因此,由服务==空值守的代码块可以由多个线程输入。

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

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 
    } 
} 

希望这是有道理的。如果不是,请留言。

+0

谢谢你。然而,只要使方法同步就可以解决问题了吗?或者还有更多呢? – digiarnie 2008-10-22 23:45:46