2008-10-22 99 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