I am working on a RichFaces-based JSF application that has com.sun.faces.numberOfViewsInSession and com.sun.faces.numberOfLogicalViews parameters set to 1 but has most of the managed beans set to a "session" scope. If reducing the memory footprint is the prime objective (with no significant deterioration to the page rendering times as well), what would be a better option?
Changing the scope to "request" so that the view state is not held for too long (unlike when the scope is set to "session").
I read somewhere that the scope of the beans could have a bearing on the size of the view (and "request" scoped beans may not necessarily be available for GC at the end of the request). I have seen a performance degradation in this case, straightaway though.
Changing the scope to "application" since a number of pages are user-agnostic and don't really change based on the authenticated user. The application scope would result in a singleton and therefore, would the overall memory associated with a bean would be significantly lower as it is not tied to a user?
Also, would this result in the JSF View lingering around for a little too long? If yes, this would make it worse than how it is currently with the session scoped beans.
Last but not the least, there are multiple forms within a view. Could this play a role as well in increasing the memory footprint?
If the beans don't really change for different users and they are going to be needed most of the time set them to Application scope. That way only one instance of the object will be instantiated and all requests will use it.
For objects that are not shared by all users using Request scope should make them eligible for garbage collection immediately instead of hanging around until the user's session expires.
That doesn't mean that the collector will run immediately but when collection is done they will be removed.
Related
An excerpt taken from a book,
For a stateless view, the component tree cannot be dynamically
generated/changed (for example, JSTL and bindings are not available in
the stateless mode). You can't create/manipulate views dynamically.
I perfectly understand the concept of going stateless as in a login form.
What I don't understand is the author's point on, JSTL and bindings are not available in the stateless mode. Please elucidate.
The author seems to be confused itself or overgeneralizing a bit too much.
The component tree can certainly still be dynamically generated/changed. This does not depend on stateful/stateless mode. The only difference with stateful mode is that those dynamic actions won't be remembered in JSF state, so they can't be restored in the postback.
It will in stateless mode continue to work fine if those dynamic changes are initiated by a non-user event during view build time, such as #PostConstruct of a request scoped bean referenced via binding attribute, or a postAddToView event listener method. It will simply be re-executed. If the method logic however in turn depends on some user-controlled variables/actions, such as request parameters or actions invoked during previous postbacks, or it is executed too late, such as during the preRenderView event, then it's not anymore guaranteed that the view will during apply request values phase of the subsequent postback become identical as it was during rendering the form to be submitted. In such case, processing the form submit may behave "unexpectedly" different as compared to a stateful view.
Each time, I go on a specific jsf page which bean is annotated with #ViewScoped, the heap increase.
How to destroy ViewScope context ? (to destroy all associated objects and clean memory heap)
Upgrading to 2.2.8 give me other errors, so i want to stay with jsf 2.2.6 implementation.
Question is relative to this : "ViewScope context is not destroyed when View Map is destroyed"
So what is the other method to achieve this ? Does it mean ViewScoped have a pegleg and that is not recommended to use it. So what is the alternative when you have a lot info to display and also ajax on the same page ?
I tried this solution too without sucess. (this post looks like the same)
I read that and also that , i have tried #PreDestroy annotation who doesn't work either in ViewScoped.
I don't want to increase too much memory heap of VM.
If i go on the same jsf page handled by a managed bean with a viewScoped, each time the memory increase until application crash.
Garbage Collector is not occuring during session even after multi-postback or if i close definitively the session and wait 5-10 minutes.
NB: #PreDestroy is still called when session is closed.
I'm learning JSF lifecycle from Oracle website and ran into ambiguous point concerning component tree rebuilding.
According to my understanding, the entire component tree will be rebuilt after every post-back request (including ajax) based on latest view-state saved, so my question is after having successfully rebuilt component tree from saved view-state what would server do with old component tree and old view-state, discard or store somewhere like view pooling for reusing later?
It depends on the state saving mode you are using. If you are using client side state saving, the information related to the view is stored into javax.faces.ViewState hidden field parameter. When the server receives the request, it creates the view from the state, process it and write the field in the response. If you are using server side state saving, the state is stored into session, so in some cases the old state is there, but there is an algorithm that discard the old views from the session.
With JSF 2.0 Partial State Saving (PSS) the view is derived from two things: the initial state and the delta state. The initial state is derived from building the view again using facelets algoritm. So what's stored as view state is just an small fraction of the overall state. The trick is very effective indeed, so after that improvement people doesn't need to care about state size anymore with JSF. That has resulted in a very good performance compared with stateless frameworks. See Understanding JSF Performance part 3 on JSFCentral
In Apache MyFaces 2.2 there is a view pool algorithm. The idea is take advantage of the state saving algorithm and use it to reuse views already built. It can give you a boost in performance of about 8-10%, but third party libraries needs to be compatible with this approach. See How to configure View Pool in Apache MyFaces. This was thought as a solution to get the "ultimate performance", but most of the time you'll do it fine using without it.
Facelets algorithm with PSS enabled is called in two points: when the view is build or restored and before render response phase to refresh the components like c:if and so on.
Why is the struts action class is singleton ?
Actually I am getting point that it is multithreaded. but at time when thousand of request hitting same action, and we put synchronized for preventing threading issue, then it not give good performance bcoz thread going in wait state and it take time to proced.
Is that any way to remove singleton from action class ?
for more info Please visit : http://rameshsengani.in
You are asking about why the Action class is a singleton but I think you also have some issues understanding thread safety so I will try to explain both.
First of all, a Struts Action class is not implemented as a singleton, the framework just uses one instance of it. But because only one instance is used to process all incoming requests, care must be taken not to do something with in the Action class that is not thread safe. But the thing is: by default, Struts Action classes are not thread safe.
Thread safety means that a piece of code or object can be safely used in a multi-threaded environment. An Action class can be safely used in a multi-threaded environment and you can have it used in a thousand threads at the same time with no issues... that is if you implement it correctly.
From the Action class JavaDoc:
Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind:
Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action.
Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.
You use the Struts Action by deriving it and creating your own. When you do that, you have to take care to respect the rules above. That means something like this is a NO-NO:
public class MyAction extends Action {
private Object someInstanceField;
public ActionForward execute(...) {
// modify someInstanceField here without proper synchronization ->> BAD
}
}
You don't need to synchronize Action classes unless you did something wrong with them like in the code above. The thing is that the entry point of execution into your action is the execute method.
This method receives all it needs as parameters. You can have a thousand threads executed at the same time in the execute method with no issues because each thread has its own execution stack for the method call but not for data that is in the heap (like someInstanceField) which is shared between all threads.
Without proper synchronization when modifying someInstanceField all threads will do as they please with it.
So yes, Struts 1 Action classes are not thread safe but this is in the sense that you can't safely store state in them (i.e.make them statefulf) or if you do it must be properly synchronized.
But if you keep your Action class implementation stateless you are OK, no synchronization needed and threads don't wait for one another.
Why is the struts action class is singleton ?
It's by design. Again the JavaDoc explains it:
An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request
The request parameters are tied to the web tier and you don't want to send that type of data into your business logic classes because that will create a tight coupling
between the two layers which will then make it impossible to easily reuse your business layer.
Because transforming web objects into model objects (and I don't mean the ActionForm beans here) should be the main purpose of Action classes, they don't need to maintain any state (and shoudn't) and also, there is no reason to have more instances of these guys, all doing the same thing. Just one will do.
If you want you can safely maintain state in your model by persisting info to a database for example, or you can maintain web state by using the http session. It is wrong to maintain state in the Action classes as this introduces the need for syncronisation as explained above.
Is there a way to remove singleton from action class?
I guess you could extend Struts and override the default behavior of RequestProcessor.processActionCreate to create yourself an Action per request
but that means adding another layer on top of Struts to change its "normal" behavior. I've already seen stuff like this go bad in a few applications so I would not recommend it.
My suggestion is to keep your Action classes stateless and go for the single instance that is created for it.
If your app is new and you absolutely need statefull Actions, I guess you could go for Struts 2 (they changed the design there and the Action instances are now one per request).
But Struts 2 is very different from Struts 1 so if you app is old it might be difficult to migrate to Struts 2.
Hope this makes it clear now.
This has changed in Struts2 http://struts.apache.org/release/2.1.x/docs/comparing-struts-1-and-2.html
*Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.) *
I don't know much about struts, but it appears that this changed in Struts 2, so perhaps you should switch to Struts 2?
It seems that all Guice's out-of-the-box Scope implementations are inherently Thread-based (or ignore Threads entirely):
Scopes.SINGLETON and Scopes.NO_SCOPE ignore Threads and are the edge cases: global scope and no scope.
ServletScopes.REQUEST and ServletScopes.SESSION ultimately depend on retrieving scoped objects from a ThreadLocal<Context>. The retrieved Context holds a reference to the HttpServletRequest that holds a reference to the scoped objects stored as named attributes (where name is derived from com.google.inject.Key).
Class SimpleScope from the custom scope Guice wiki also provides a per-Thread implementation using a ThreadLocal<Map<Key<?>, Object>> member variable.
With that preamble, my question is this: how does one go about creating a non-Thread-based Scope? It seems that something that I can use to look up a Map<Key<?>, Object> is missing, as the only things passed in to Scope.scope() are a Key<T> and a Provider<T>.
Thanks in advance for your time.
It's a bit unclear what you want - you don't want scopes that are based on threads, and you don't want scopes that ignore threads.
But yes, scopes are intended to manage the lifecycle of an object and say when an instance should be reused. So really you're asking "what are the other possibilities for re-using an instance beyond 'always use the same instance', 'never use the same instance', and 'use an instance depending on the execution environment of the current thread'?"
Here's what comes to mind:
Use the same instance for a fixed amount of time. The example here would be of a configuration file that's reloaded and reparsed every ten minutes.
Perform some network call to query whether a given object should be re-used (maybe it's a fast call to determine whether we need to reconstruct the object, but the call for reconstructing the object is slow)
Re-use the same object until some outside call comes in telling us to reload
Re-use the same object per thread, but not with a scope that's explicitly entered and left like the servlet scopes. (So one instance per thread)
A "this thread and child threads" scope that is based on an InheritableThreadLocal, not a plain ThreadLocal.
Related to that, a Scope and a threadpool-based ExecutorService that work togehter so that instances are shared between a thread and jobs it submits for background execution.
Pull instances out of a pool; this is tricky, since we'd need a good way to return objects to the pool when finished. (Maybe you could combine this idea with something like the request scope, so that objects can be returned to the pool when the request ends)
A scope that composes two or more other scopes, so for example we could get a configuration object that is re-read every 10 minutes except that the same instance is used through the lifetime of a given request.