FacesContext life cycle?

Looking through javadoc FacesContext , I came across this sentence

The instance remains active until its release () method is called, after which additional references to this instance are not resolved. Although the FacesContext instance is active, it must not reference any thread other than the one that uses the servlet container that runs this web application to process this request.

Does this mean that FacesContext will never be sent to garbage collection, and the instance will be destroyed only when the current web application stops (the server is stopped)?

Is FacesContext after a singleton pattern? In this case, how will it behave when there are several requests and start rendering the response at the same time, since it only serves one request per time?

+7
source share
1 answer

Does this mean that FacesContext will never be sent to garbage collection, and the instance will be destroyed only when the current web application stops (the server is stopped)?

No, you are reading this wrong. FacesContext lives as long as one HTTP request. This (in fact, “maybe” is the best word) will not immediately be GC'ed if you incorrectly refer to it somewhere in your own code outside of its scope. For example. as a property of a managed bean session that lives longer than one 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 do not do this anywhere in your code, and thus you always get the current instance in the local mode of the method, then it will have the opportunity 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(); } } 

Note that this GC behavior is not specific to JSF / FacesContext , it is just specific to underlying Java in general.


Is FacesContext after a singleton pattern? In this case, how will it behave when there are several requests and start rendering the response at the same time, since it only serves one request per time?

No, it's definitely not a singleton. This is a ThreadLocal instance created by FacesServlet right after the service() method is introduced and destroyed with FacesServlet right before leaving the service() method. Thus, there is only one instance for each request (and therefore not for the application). Note that one HTTP request counts as one separate stream. There may be multiple threads (read: requests), and thus, there may be multiple instances of FacesContext during the life of the application. Its main template is a facade scheme , but this is not related to the fact that this is ThreadLocal .

See also:

+10
source

All Articles