问题描述
遍历FacesContext
的 javadoc ,我碰到了这句话
While going through the javadoc of FacesContext
, I came across this sentence
这是否意味着FacesContext
将永远不会进行垃圾回收,并且仅当当前Web应用程序停止(服务器停止)时,实例才会被破坏?
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
是否遵循单例模式?在这种情况下,如果同时有多个请求并同时呈现响应,那么它将表现如何?
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?
推荐答案
不,您读错了. FacesContext
的寿命与单个HTTP请求一样长.如果您在您自己的代码中超出其范围的任何地方错误地引用了它,那么(实际上,可以"是一个更好的词)将不会立即被GC处理.例如.作为会话作用域受管bean的属性,其寿命比单个HTTP请求更长:
No, you read it wrongly. The FacesContext
lives as long as a single HTTP request. It will (actually, "can" is a better word) not immediately be GC'ed if you incorrectly reference it anywhere in your own code beyond its scope. E.g. as a property of a session scoped managed bean which lives longer than a single HTTP request:
@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处理.
If you aren't doing that anywhere in your code, and thus you're always obtaining the current instance in method local scope, then it will have the chance to be properly GC'ed.
@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.
Please note that this GC behavior is not specific to JSF/FacesContext
, it's just specific to basic Java in general.
不,绝对不是单例.这是一个 ThreadLocal
实例,在进入service()
方法之后立即由FacesServlet
创建,并在离开service()
方法之前由FacesServlet
销毁.因此,每个请求(因此不是每个应用程序)只有一个实例.请注意,一个HTTP请求算作一个单独的线程.可能有多个线程(读取:请求),因此在应用程序生存期内可能存在FacesContext
的多个实例.其主要模式是外观模式,但这与ThreadLocal
无关.
No, it's definitely not a singleton. It's a ThreadLocal
instance which is created by FacesServlet
right after the service()
method is entered and destroyed by the FacesServlet
right before the service()
method is left. Thus, there's only one instance per request (and thus not per application). Note that one HTTP request counts as one separate thread. There can be multiple threads (read: requests) and thus there can be multiple instances of the FacesContext
during application's lifetime. Its main pattern is the facade pattern, but that's further not related to it being a 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
这篇关于FacesContext的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!