gpt4 book ai didi

multithreading - struts Action 单例

转载 作者:行者123 更新时间:2023-12-03 12:44:23 26 4
gpt4 key购买 nike

为什么struts的action类是singleton?

实际上我明白它是多线程的。但是当数千个请求达到相同的操作时,我们设置了同步以防止线程问题,然后它不能提供良好的性能 bcoz 线程进入等待状态并且需要时间来处理。

这是从 Action 类中删除单例的任何方法吗?

欲了解更多信息,请访问:http://rameshsengani.in

最佳答案

您在问为什么 Action 类是单例的,但我认为您在理解线程安全方面也存在一些问题,因此我将尝试对两者进行解释。

首先,Struts Action 类不是作为单例实现的,框架只使用它的一个实例。但是因为只使用一个实例来处理所有传入的请求,所以必须注意不要在 Action 类中做一些不是线程安全的事情。但问题是:默认情况下,Struts Action 类不是线程安全的 .

Thread safety意味着一段代码或对象可以在多线程环境中安全使用。一个 Action 类可以在多线程环境中安全使用,您可以让它同时在一千个线程中使用,没有任何问题...即 如果你正确地实现它 .

来自 Action class JavaDoc :

Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind:

  • Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action.

  • Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.



您可以通过派生和创建自己的方式来使用 Struts Action。当你这样做时,你必须注意遵守上述规则。这意味着这样的事情是不可以的:
public class MyAction extends Action {
private Object someInstanceField;
public ActionForward execute(...) {
// modify someInstanceField here without proper synchronization ->> BAD
}
}

你不需要同步 Action 类,除非你在上面的代码中对它们做错了什么。问题是执行到您的操作的入口点是 execute方法。

这个方法接收它需要的所有参数。您可以在 execute 中同时执行一千个线程。没有问题的方法,因为 每个线程都有自己的执行栈对于方法调用,但不适用于在所有线程之间共享的堆中的数据(如 someInstanceField )。

修改 someInstanceField时没有正确同步所有线程都会随心所欲。

所以是的,Struts 1 Action 类不是线程安全的,但从某种意义上说,您不能在其中安全地存储状态(即使它们有状态),或者如果您这样做,则必须正确同步。

但是,如果你保持你的 Action 类实现无状态,你就可以了,不需要同步,线程也不会互相等待。

Why is the struts action class is singleton ?



这是设计使然。 JavaDoc 再次解释了它:

An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request



请求参数与 Web 层相关联,您不希望将这种类型的数据发送到业务逻辑类中,因为这会产生紧密耦合
在这两个层之间,这将使您无法轻松地重用您的业务层。

因为将 web 对象转换为模型对象(这里我不是指 ActionForm bean)应该是 Action 类的主要目的,所以它们不需要维护任何状态(也不应该),而且,没有理由有更多这些家伙的实例,都在做同样的事情。只有一个会做。

如果您愿意,您可以通过将信息持久保存到数据库来安全地维护模型中的状态,或者您可以使用 http session 来维护 Web 状态。在 Action 类中维护状态是错误的,因为这引入了如上所述的同步需求。

Is there a way to remove singleton from action class?



我猜你可以扩展 Struts 并覆盖 RequestProcessor.processActionCreate 的默认行为根据请求为自己创建一个操作
但这意味着在 Struts 之上添加另一层以改变其“正常”行为。我已经看到这样的东西在一些应用程序中变坏了,所以我不推荐它。

我的建议是让您的 Action 类保持无状态,并使用为其创建的单个实例。

如果你的应用是新的并且你绝对需要有状态的 Action ,我想你可以选择 Struts 2(他们改变了那里的设计, Action 实例现在每个请求一个)。
But Struts 2 is very different from Struts 1因此,如果您的应用程序较旧,则可能很难迁移到 Struts 2。

希望这现在清楚了。

关于multithreading - struts Action 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com