gpt4 book ai didi

jsf-2 - FacesContext 的生命周期?

转载 作者:行者123 更新时间:2023-12-04 10:53:14 24 4
gpt4 key购买 nike

同时通过javadoc of FacesContext ,我遇到了这句话

The instance remains active until its release() method is called, after which no further references to this instance are allowed. While a FacesContext instance is active, it must not be referenced from any thread other than the one upon which the servlet container executing this web application utilizes for the processing of this request



这是否意味着 FacesContext永远不会进行垃圾收集,并且只有在当前网络应用程序停止(服务器停止)时才会销毁实例?

FacesContext遵循单例模式?在这种情况下,当多个请求同时来渲染响应时,它会如何表现,因为它每次只服务一个请求?

最佳答案

Does this mean that FacesContext will never go for garbage collection, and the instance will be destroyed only when the current-webapplication stops (server is stopped)?


不,你读错了。 FacesContext与单个 HTTP 请求一样长。如果您在 中的任何地方错误地引用了它,它(实际上,“可以”是一个更好的词)不会立即被 GC 处理。您自己的 超出其范围的代码。例如。作为 session 范围托管 bean 的属性,它的生命周期比单个 HTTP 请求更长:
@ManagedBean
@SessionScoped
public class BadSessionBean {

// Bad Example! Never do this! Not threadsafe and instance can't be GC'ed by end of request!
private FacesContext context = FacesContext.getCurrentInstance();

}
如果您没有在代码中的任何地方这样做,因此您总是在方法本地范围内获取当前实例,那么它将有机会被正确 GC 处理。
@ManagedBean
@SessionScoped
public class GoodSessionBean {

public void someMethod() {
// OK! Declared in method local scope and thus threadsafe.
FacesContext context = FacesContext.getCurrentInstance();
}

}
请注意,此 GC 行为并非特定于 JSF/ FacesContext ,它通常只特定于基本的 Java。

Is FacesContext following singleton pattern? In that case, how will it behave when multiple request and coming for rendering response simultaneously as it serves only one request per time?


不,它绝对不是单例。这是一个 ThreadLocal FacesServlet 创建的实例紧跟在 service() 之后方法由 FacesServlet 进入和销毁就在 service() 之前留下方法。因此,只有一个实例 每个请求 (因此不是每个应用程序)。请注意,一个 HTTP 请求算作一个单独的线程。可以有多个线程(读取:请求),因此可以有 FacesContext 的多个实例。在应用程序的生命周期内。它的主要图案是 facade pattern ,但这与它是 ThreadLocal 无关。 .
也可以看看:
  • java threadlocal singleton - what is it?
  • How to initialize an API in servlet environment
  • Examples of GoF Design Patterns in Java's core libraries
  • 关于jsf-2 - FacesContext 的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229901/

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