将类从线程不安全迁移到线程安全



Background

Apache Action 类不是线程安全的。但是,这只有在实现基类之后才能实现,系统中所有其他类都依赖于基类。基类使用许多实例变量:

  private HttpServletRequest request;
  private ArrayList inputParams = new ArrayList();
  private Connection connection;
  private String outputParameter;
  private boolean exportEnabled;

幸运的是,这些变量的所有用法都是通过访问器方法完成的,独占。例如:

  public boolean getExportEnabled() {
    return this.exportEnabled;
  }
  public void setExportEnabled( boolean exportEnabled ) {
    this.exportEnabled = exportEnabled;
  }

问题

基类在多线程 Servlet 环境中运行。

解决方案#1

为了解决这个问题,我正在考虑使用与会话键控的哈希图。但是,这需要重写所有方法和依赖代码:

  private static HashMap sessionVariables = new HashMap();
  public boolean getExportEnabled( HttpSession session ) {
    return getSessionVariables().get( session.getId() + '.exportEnabled' );
  }
  public void setExportEnabled( boolean exportEnabled, HttpSession session ) {
    getSessionVariables().put( session.getId() + '.exportEnabled', exportEnabled );
  }

这是大量的工作,并且可能会引入错误。

解决方案#2

可以将基类更改为"空"类。这个空类将具有单个方法:

  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response )
    throws Exception {
    // Instantiate "this" and forward the request?
  }

但它必须知道要实例化的适当基类,或者可能实例化自身的新版本来处理调用。

更新 #1

我相信 Struts 架构做到了以下几点:

  1. 创建 Action 子类的实例。
  2. 为每个请求重复使用同一实例。
  3. 接收新连接时获取线程(从线程池)。
  4. 从线程调用 Action 子类上的execute
  5. 使用不同的线程处理多个新连接。

将在对象的同一实例上调用相同的execute方法,从而导致不安全的行为,因为子类具有实例变量。

更新 #2

以下解决方案似乎可以解决问题:

  public ActionForward execute(
          ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response ) throws Exception {
      ((MyClass)clone()).executeClone( mapping, form, request, response );
  }
  public ActionForward executeClone(
          ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response ) throws Exception {
      // Former "execute" method code goes here.
      // ...
  }

原来的execute方法被重命名为executeClone。新的execute实现创建当前类的克隆,随后调用executeClone 。这种微创技术避免了引入新的错误,同时使类线程安全。

问题

使代码线程安全同时最大限度地降低引入错误的风险的最可靠方法是什么?

谢谢!

解决方案 #1 很危险,因为它假定会话是线程安全的,但事实并非如此。有人可能在同一会话中同时发出两个请求。

解决方案#2可以通过使您的基类实现Cloneable来轻松实现。然后它可以克隆自身,设置克隆的实例变量,然后调用super.execute() 。如果您认为更改设计以使基类正确线程安全太难,这可能是一个简单的方法。

使代码线程安全同时最大限度地降低引入错误的风险的最可靠方法是什么?

对此没有普遍的答案。 使类线程安全需要做什么取决于类的作用、它的 API 设计......以及您需要什么级别的线程安全。 在某些情况下,使某些东西成为线程安全的东西甚至不切实际;例如,阅读 javadoc 以获取Collections.synchonizedList并查看它如何处理 iterator() 方法。

最新更新