Singleton Object Created for each Request - java

I want to create a singleton object whose scope is basically only the request. This will be used to collect the errors and we need to send error whenever we send the response back.
Can anyone provide pointers toward this thing?
I am also using spring.
I tried using Spring container singleton object scope session or request but still my object is holding values from the earlier request
I am using this error object with AspectJ. Will that may cause problem on static binding?

how about
//sync this code
if(request.getAttribute("someKey") == null){
// create object and set it
}

If you set the Object life cycle in the Spring container to be per request then it should only exist for that HttpRequest.
Generally for direct injection containers like Spring when you set the object life cycle or object scope to be per request then it should create an new instance of the object for each http request that it recieves.
If it is not doing this then I would assume that it is more than likely something to do with your configuration.
Singleton is the defualt for the spring container when creating beans I think so you have to specifically set the object scope to per request.
Bean Scopes
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html

I'm not sure that singleton is what you want here - if two requests arrived concurrently they would share the singleton object, and their errors will get mixed up.
Is it possible to create an object to hold the errors and put that in to a ThreadLocal object. The scope of the object will be constrained by the request, and access to it in the ThreadLocal object is easily achieved from within your application without having to pass a refernce to the object around.

You can use ThreadLocal.

Related

Create a single instance of HashMap in Java throughout the session

I am working on a project wherein I need to store a set of keys and values throughout the session of the program execution. Meaning when the server is up, I want to have a map which stores data and is same for multiple requests made in that session.
So for creating this map, should I make a static Map or create a singleton bean for it and use autowiring? Which is better?
I used the static map, but noticed that even after stopping the server and running it again, the map instance was having values from previous session, instead it should have been null in the beginning of the request. The objects were not getting destroyed properly.
Does this behavior is improved if I'll use beans?
You have to define what is a Session.
Usually, in a Web project, a Session is related to an HTTP Session. These are managed in Spring by #Scope(value = WebApplicationContext.SCOPE_SESSION). The Bean will have a proxy, managing the instances of your Service automatically.
In this case, you do not want to use a Static Map. Indeed, a static object is global to your program, and only one instance will exist at any time, like a Singleton.
If you define a Session as the start and end of your server process, then fine.
So for creating this map, should I make a static Map or create a singleton bean for it and use autowiring?
This is close to the same thing. The only difference is how it will be instantiated. A static Map will be created by the JVM as soon as your Class is loaded. A Singleton Bean will be created by Spring at the first use.
The main advantage of the Bean, in your case, is the Inversion of Control for your Unit Tests.
I used the static map, but noticed that even after stopping the server and running it again, the map instance was having values from previous session
Usually, an object will lose its data when the server is closed, unless your Map has been Serialized by the server and stored in a session file on the disk. Maybe you should try to move your static Map to its own Class.
Does this behavior is improved if I'll use beans?
No, the behavior will be the same.
Don't forget that, as a singleton, your Map must be synchronized with Collections.synchronizedMap(). Otherwise, you will have surprises when using it.

Xpages: managedBean is constantly "losing" global Domino Session object

I'm in the process of building a managedBean for an Xpages application. Currently the bean is registered in faces-config at view scope because I need it to re-initialize on every page load (see below). The bean's constructor initializes several class variables whose values are referenced all over the entire class's code. One of those variables is a Domino session object, another example is the current document datasource:
private Session session;
private DominoDocument ds;
Both are initialized within the constructor as
session=DominoUtils.getCurrentSession();
ds=(DominoDocument) resolveVariable(dsName);
(resolveVariable is an internal helper method; don't think I need to explain that here)
Apart from the constructor and the various helper methods there are also some other public methods within the same class that are called on button clicks. Most of those additional methods make use of the same document datasource, as well as the current session object.
What's happening is that my additional methods can access and use the global datasource object (ds) but if they try to access the global session object an error is thrown; further down the stack trace I find what seems to cause the error:
NotesException: Object has been removed or recycled
There's no recycling at all in my code right now, the session object must get lost somewhere on the way.
As a workaround I started passing the session object from SSJS into each method as in
public void testMethod(Session s){
System.out.println("my name is " + s.getEffectiveUserName());
}
Which is working fine. But why is it that the bean object keeps forgetting the global session while it can remember all the other objects and variables?
BTW: I tried to bind my managedBean to a session scope but that doesn't help at all. And yes, I even restarted the entire server after making that change...
All Domino objects coming from the runtime are recycled at the end of every request. If you want to access any of them, you should re-fetch them from the environment when they're needed and not store references within your mean (you could use transient refs, but you wouldn't gain much). So the quick fix is to replace each use of the session in your class with that DominoUtils.getCurrentSession() call.

How to share complex java objects across views servlets methods within a spring controller without making those objects singleton bean?

It's as simple. In Spring MVC, how and where do I store a complex java object so that it is available across the action servlets. For example if an ajax is called on next page, the business object from within some previously called servlet, stored somewhere should be accessible in that ajax action method in java. I did this by creating a singleton bean but it failed when multiple users hit the application. User outputs are affected among each other. I need to achieve this in a non-singleton manner.
You can store objects in your request object:
request.setAttribute("key", valueObject);
To get the object, simply use
request.getAttribute("key");
Or, as Subir Kumar Sao said in the comments, use the session to store your stuff:
request.getSession().setAttribute("key", valueObject);
and
request.getSession().getAttribute("key");
You can use either
request.setAttribute("key", valueObject);
request.getAttribute("key");
or
session.setAttribute("key", valueObject);
session.getAttribute("key");
Difference between them : Request-scoped attribute is visible only while current request is processed. Session-scoped attribute is persistent between several requests from the same user.
You should keep your objects on session level. As long as the session is alive, you can access your session level variables, regardless of the requests.
request.getSession().getAttribute("key");
request.getSession().getAttribute("key", value);
Keep in my mind that once a session level attribute is set, that is always there until, session is killed or invalidated. So you may need to remove the attribute according to your logic.
request.getSession().removeAttribute("key");

External thread callback to a session scoped Spring bean

I have a Spring Web MVC application where i need to use an external device driver which returns information in an asynchronous manner every time the device gathers some new data. We need to pass an object at the begging to the start read method. This object implements an API defined interface which declares the callback method.
The problem raises when this callback method needs to manipulate some bean in Spring's session scope. Because the callback gets called in the Thread of the driver when the callback implementation wants to access a Spring bean it yields an exception saying that the current thread is not in Spring's managed scope.
I'm wondering if there's any way to make the object which is implementing the callback interface into some kind of proxy which knows information about the context of the session which constructed it so this way it can invoke bean methods through Spring's context object?
I think you are approaching the problem from the wrong side. I guess you want the device driver callback to put some results in the user session. But this is not enough to display that data, so (guessing again) probably some long-polling is involved, looking into the session through session-scoped bean.
With this assumption I advice you to generate some sort of unique requestId every time you call the back-end driver and put that requestId both in the HTTP session and in the callback. When the callback is called, it pushes the results into some sort of map, where key is the assigned requestId. Now the client (who knows the requestId as well) can look into the map and fetch the results. You must remember about the synchronization (which is also the case with normal HttpSession).
If you have some more advanced way of notifying clients (Comet? WebSockets?) this can also be done in this callback.
Note that technically you can pass an instance of HttpSession object into the callback instance (but as you can see this does not work with Spring session-scoped beans) but passing session around doesn't seem like a good design. It is simply better to provide a level of indirection. What if, in the future, you would like to reuse that code with command-line or desktop client?

Spring, create a bean from deserializing

I've not used Spring too much, so I might be missing something obvious. Anyway, this is the question:
Say you have a Spring managed bean that is a networking client. After you call a method on it you get some object back, say it is a List
Now I want to process that List into something more useful for the rest of my application, say it is of a MyBusinessBean type.
How do I avoid doing a
new MyBusinessBean(List<String> info)
?? If I do this it becomes an object that is not part of the context.
I'm doing something like:
MyBusinessBean myBean = (MyBusinessBean) applicationContext.getBean("myBusinessBean", info);
However I keep reading everywhere that this is a signal of something not being done properly, since I am making my code context aware. What is the proper Spring way of doing this?
The second way is what you do in Spring. Calling "new" means you're breaking the model.
But don't assume that every call to "new" is eliminated by Spring. Every object need not be under Spring's control. Sometimes you just gotta call "new", usually in the scope of a single method. Create the object, use it, GC it - no Spring bean factory needed.
If you want to give an object in your app access to that List after serialization, simply pass the reference. You don't need the Spring bean factory in the situation you've described, because you've already got the serialized the object from the server.

Categories