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)?
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();
}
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();
}
}
Please note that this GC behavior is not specific to JSF/FacesContext
, it's just specific to basic Java in general.
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?
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
.
See also: