Lifecycle of FacesContext?

依然范特西╮ 提交于 2019-11-30 20:22:15
BalusC

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!