2012-12-08 72 views
0

開始:我是開源軟件的新手。 (Apache-Tomcat/Java/Restletframework)線程安全和靜態子類

這是我的問題: 我正在用Restlet框架構建一個應用程序。我不知道我的編碼/方法 是否是線程安全的!?有人可以告訴我,我是否正確地編碼?或者我絕望地失敗了?

構建:

  • CLASS A將被客戶端調用。 (其餘請求)
  • CLASS A(路由器)將調用B類
  • CLASS B是我的中央請求處理程序,此B類調用另一個C類
  • CLASS C是被請求的實際服務,在這個例子中,登錄服務 -

正如你所看到的登錄子類是靜態的。這是一個線程安全的結構嗎?如果多個線程訪問某些共享狀態

問候

CLASS A

public class MyStartApplication extends Application { 


//Creates a root Restlet that will receive all incoming calls. 

@Override 
//public synchronized Restlet createInboundRoot() { //synchronized? 
public Restlet createInboundRoot() { 


    //Create a router that routes each call to a new instance of a Resource. 
    Router router = new Router(getContext()); 

    // First we use MODE_START_WITH to determine the requested destination 
    // A TRAPDOOR for all requests for this TEST 
    // We reroute it to THE CENTRAL RESTLET-WRAPPER 
TemplateRoute route = router.attach("/testmywrapper/", RestletWrapper.class); 
    route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); 


    // Return the response to caller 
    return router; 


} 

} 

CLASS B

public class RestletWrapper extends ServerResource { 

@Get 
public JSONObject start() { 

    JSONObject returnObj = null; 

    switch(operation){ 
    case "login": 
     returnObj= LoginUser.login(queryparams); 
     break; 
    } 

    Return returnObj 
} 
} 

C類

public class LoginUser { 


public static JSONObject login(JSONObject queryparams) throws Exception { 
    do some stuff 
    return object 
} 
} 

回答

0

線程安全可能是一個問題。

除非隱藏在「做某些事情」後面的代碼使用靜態字段或單例,否則應該沒有線程安全問題:所有變量都是登錄方法的局部變量,因此不會在線程之間共享。

+0

因此,子類被定義爲「靜態」的事情不是線程不安全的perse? – user1887511

+0

我也想知道第一個Restlet-Starter-Application中的「sychronized」關鍵字,我知道它是從新的Restlet-version中的子類createInboundRoot()中移除的......,我必須在較舊的Restlet版本,和/或不會影響線程安全性? – user1887511

+0

我不知道restlet。閱讀手冊。另外,你沒有任何「靜態子類」。你有一個靜態方法。一個只使用局部變量的靜態或不靜態方法本質上是線程安全的。如果這是登錄方法的情況,並且如果queryparams對象不在線程之間共享(並且看起來它不在線程之間共享),那麼此方法是線程安全的。 –