【问题标题】:Is it ok to make all methods called from a servlet doGet() static to avoid synchronization?是否可以将所有从 servlet doGet() 调用的方法设为静态以避免同步?
【发布时间】:2012-11-05 15:53:00
【问题描述】:

我有一个执行各种业务逻辑的 servlet。我想避免这样的同步:

@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);
}

我不会使用任何静态变量,并且我的所有方法调用都假定是线程安全的。有什么不明显的缺点吗?

【问题讨论】:

    标签: servlets concurrency static synchronized


    【解决方案1】:

    我不会使用任何静态变量,并且我的所有方法调用都假定是线程安全的。

    在这些条件下,您既不需要同步也不需要静态方法。只需使用 servlet 或其他服务类的实例方法即可。

    【讨论】:

    • 很公平,静态方法只是为了确保我或其他处理代码的人不会意外使用或引入实例变量。
    • @StefanSeidel 那么是什么阻止他们引入静态变量呢?我真的认为你在这里叫错了树。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-06-26
    • 2012-11-12
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多