"Stateful: These beans can hold client state across method invocations. This is possible with the use of instance variables declared in the class definition. The client will then set the values for these variables and use these values in other method calls."
What does maintaining state across method calls mean ?
sorry for the noobness of my question.
You can think of it as the HttpSession on a web application. What you save on HttpSession is available across different requests to the web server. Likewise what you store as class variables in a session EJB is available across different method invocations done on the same session EJB.
Refer:
Lookup returns new instance of Stateful session bean
http://www.javaworld.com/article/2071724/java-web-development/ejb-fundamentals-and-session-beans.html
Statefullness is bad when it comes to concurrency. For Example you have one Statefull Bean, UserRegistrationBean which stores email then if two users try to register at the same time in a race condition one user overwrite the other one's email.
Statefullness requires synchronized access to the state which is costly.
Related
I am working on a JSP web app to use HttpURLConnection to receive and transfer data from/to a Parse.com database via their REST services. The web application will need to be deployed on Google App Engine or Amazon Web Services.
I have defined a ParseUtils class that is responsible for getting or posting data from or to the Parse database tables through HttpURLConnection class. It has many functions in it and each function establishes a HttpURLConnection for a particular Parse table.
Hope I have given out as many details as needed. My question is: should the ParseUtils class be declared and initialized in the ServletContext when the ServletContext gets initialized or be defined as a session-scoped object for each session? Any best practice?
Thanks!
Connection objects are typically not "shareable" in the concurrent access sense of the word (they are reusable however, in that turn-based access is permissible in a managed environment/execution context). Given that HttpURLConnection is not threadsafe, there's no reason to keep it in a global, shared-state component like the ServletContext.
That leaves you with the request and session scopes, and also a need to answer the following questions
What's the overhead associated with establishing a new HttpURLConnection for each request?
What's the likelihood/need that a single connected client would need to open two pipes, i.e. two HttpURLConnections in a single session either by way of a new window or tab
The answer to #1 is the overhead is there, but very slight; if there's even a slight chance of #2 being a possiblity, you definitely want to open a new HttpURLConnection per request, or better yet consider springing for Apache's HttpClient to take advantage of stuff like connection pooling
What I am unsure is what'd happen if a user (session A) is trying to call a function of ParseUtils to post some data while at same time another one is trying to call the same function or different function using another session (session B). Would those requests be queued?
If ParseUtils does not store any data in its instance variables, you are perfectly safe. Local methods are thread safe and can be invoked concurrently provided it does not use instance variables.
As an analogy, think how a single instance of a Servlet can process multiple requests. The request processing methods (doGet() or doPost()) are local methods of the servlet that are accessed concurrently to serve multiple parallel requests. You are safe as long as you do not have mutable request data stored in instance variables.
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");
We have an application that contains a chat. We are using the Node.JS's IO Socket to make the push to the client. The client, when authenticated, is connecting to a room with his/her id as identifier of the room. We did it because there're some singletons that push some notifications to the client, independent of his/her session. The chat's spring bean is SessionScoped.
The problem we're facing happens when the same client login in the system with two different browsers. Two sessions are created, so there's two spring beans of the chat operating. Since both beans push to the room identified by the user id, in the client side, the same message arrives two times. The number of duplicated messages increases with the number of browsers.
So, I wanna create a custom scope for the Spring. This scope must be shared between all the clients logged in with the same login and must be destroyed as soon as all the sessions logged in with this login be destroyed.
I think this scope will need a map with all the sessions for each login and it'll need to listen for the destruction of these sessions. Can someone help me with this?
I found the following solution:
I created a spring's singleton bean that has a Map created with MapMaker of Guava. The map has a weak value (more about weak references here: http://weblogs.java.net/blog/2006/05/04/understanding-weak-references). Then I have a spring's session bean. This session bean ask the singleton for an instance for the chat passing the id of the client. The singleton, verify if there's something in the map. If it doesn't have, it creates a new chat instance, puts in the map and returns it. The session bean maintains a reference for this chat instance. If the user login in a different browser, a new session bean will do the same. This time, it'll get the instance saved in the map. When there's no more session beans with references to the chat instance, it'll be garbage collected, since the map has a weak reference for it.
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?
Im really new to java, jsf, jsp, and I need to learn how it works quickly. So the website Im using to practise has some terms etc that I dont know what they mean and Im hoping somebody can explain what they mean and how/what they are used for:)
Requestscoped
Applicationscoped
Sessionscoped
EntityManager
and could someone walk me through what these lines do?
#RequestScoped
public class Dao {
#DataRepository
#Inject
private EntityManager entityManager;
First of all, in Java (5 and higher), "things" starting with a # (e.g. #Deprecated) are called annotations.
Annotations provide data about a
program that is not part of the
program itself. They have no direct
effect on the operation of the code
they annotate.
Your JavaBeans needs to be configured to a scope if you want to use it in JSF (Definitions can be found here).
#RequestScoped: Objects with this scope are visible from the start of the request until the end
of the request. Request scope starts at the beginning of a request and ends when the
response has been sent to the client. If the request is forwarded, the objects are visible
in the forwarded page, because that page is still part of the same request/response
cycle. Objects with request scope can use other objects with none, request, session,
or application scope. If you have to think it in terms of servlet, the managed bean is stored in the HttpServletRequest until the end of the request (when the response is sent to the client). After that, the bean no longer exists in the request.
#SessionScoped: An object with session scope is visible for any request/response cycle that
belongs to a session. Objects with this scope have their state persisted between
requests and last until the object or the session is invalidated. Objects with session
scope can use other objects with none, session, or application scope. Basically, these objects are stored in a HttpSession (refer to Servlets again). Each session has a session ID (known as JSESSIONID) that the bean is associated with.
ApplicationScoped: An object with application scope is visible in all request/response cycles
for all clients using the application, for as long as the application is active. In terms of Servlet, this could be, managed bean stored in a ServletConfig.
#NoneScoped: Objects with this scope are not visible in any JSF page. When used in the configuration file, they indicate managed beans that are used by other managed beans in the application. Objects with none scope can use other objects with none scope.
For EntityManager, this is associated with persistence context. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities. For more, refer to the JPA (Java Persistence API) Specification, or Hibernate.
#Inject, means that the instance is injectable. They follow the infamous crase word of Depency Injection or Inversion of Control (IOC). What this basically mean, is that when the resource (in your case EntityManager entityManager is needed, the JEE container instantiates the resource for you (without you needed to instantiate it directly through e.g. a constructor, etc.).
I have no clue what #DataRepository means. Never seen it before.
I hope this helps you.
These terms are usually associated with a dependency injection framework like guice and not with java in particular.
http://code.google.com/p/google-guice/wiki/Scopes describes the various scopes that are built into guice.
By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (#Singleton), a session (#SessionScoped), or a request (#RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.