2012-11-05 84 views
0

我有一個執行各種業務邏輯的servlet。我想避免的同步是這樣的:通過使所有調用的方法靜態和執行它像這樣是否可以通過servlet調用doGet()靜態方法來避免同步?

@Override 
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException { 
    synchronized (MyServlet.class) { 
     various(); 
     calls(); 
     and_logic(_req, _resp); 
    } 
} 

@Override 
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException { 
    _doGet(_req, _resp); 
} 

private static void _doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException { 
    various(); 
    calls(); 
    and_logic(_req, _resp); 
} 

我不會使用任何靜態變量和我所有的方法調用假設是線程安全的。有沒有明顯的缺點?

回答

1

我不會使用任何靜態變量,並且我所有的方法調用都被假定爲線程安全的。

在這些條件下,您既不需要同步也不需要靜態方法。只需使用servlet或其他服務類的實例方法即可。

+0

不夠公平,靜態方法只是爲了確保我或其他人在代碼上工作時不會意外地使用或引入實例變量。 –

+0

@StefanSeidel那麼阻止他們引入靜態變量是什麼呢?我真的認爲你在這裏吠叫錯了樹。 – EJP