In my project, I forgot to close the entity manager for each operation. After some time, I got exception due to excessive connections to mysql server. Does this mean that each entity manager establish the connection? What will happen when we forget to close the connection? I have used only one entity manager factory.
Assuming that you are using an application-managed entity manager, then you are responsible for initializing and closing the entity manager. One the other hand, if you are relying on the container to inject the entity manager into your session beans (or any managed classes), then the container is responsible for ensuring that the entity manager is closed.
Usually, the entity manager is not responsible for creating connections to the database. It would instead use a connection pool, that is defined in persistence.xml. This is true of both JTA entity managers and resource-local entity managers; JTA entity managers rely on a JTA datasource provided by the application server environment, while resource-local entity managers create and manage their own pools.
If you do not close entity managers, and if you continue to create new instances of them, then it is possible for you to exhaust connections in the JTA datasource (for JTA entity managers) or hit a server-defined limit on client connections (for both JTA and resource-local entity managers). Each database instance would be configured to accept no more than a certain number of connections. If the number of connections established by all clients, exceeds this limit, the server will simply drop addition connections. If you open entity manager instances that request for additional connections from a pool (for JTA entity managers), or create new pools (for resource-local entity managers), then it is very much likely that the pool itself might be exhausted, or too many connections would have been opened.
Since you cannot close the connections directly, or even resize the connection pools from your application, it is quite obvious that you must close entity manager instances when you no longer need them; this will automatically release the connections that were established for the entity manager.
Also, it would be wise to look at using a well-tuned and adequately sized connection pool for every entity manager instance, in case you are using resource-local entity managers for a reason. If you are using a JTA entity manager, consider using container-injected entity managers and a JTA datasource that is backed by a well-tuned and adequately sized connection pool.
In any case - if you explicitely open EntityManager (get it from EMFactory), then you should close it. Whether it takes connection (which seems to be your case) or not depends on settings that is rather JPA provider related. On our project, EM opens connection for every query and returns it back immediately (closes). But there are other options - keep the connection, or connection that follows transaction lifecycle.
As an example, here are settings for OpenJPA. I'd say that if EM opened the connection for query/transaction, than you wouldn't hit the problem. It seems that your EM takes the connection and holds it.
In any case, you should close the EM if you created it. Best practice is to do it in the same method if possible, so it's easy to review the correctness, and to do so in finally block.
Related
Rest is meant to be stateless. Client maintains application state and server maintains resource state. In statefull application where does that state is maintained? Is it maintained in session or in In-memory database or anything else?
From the oracle documentation:
What is a Stateful Session Bean?
A stateful session bean is a session bean that maintains conversational state.
Stateful session beans are useful for conversational sessions, in which it is necessary to maintain state, such as instance variable values or transactional state, between method invocations. These session beans are mapped to a single client for the life of that client.
A stateful session bean maintains its state between method calls. Thus, there is one instance of a stateful session bean created for each client. Each stateful session bean contains an identity and a one-to-one mapping with an individual client.
When the container determines that it must remove a stateful session bean from memory (in order to release resources), the container maintains the bean's state by passivation (serializing the bean to disk). This is why the state that you passivate must be serializable. However, this information does not survive system failures. When the bean instance is requested again by its client, the container activates the previously passivated bean instance.
The type of state that is saved does not include resources. The container invokes the ejbPassivate method within the bean to provide the bean with a chance to clean up its resources, such as sockets held, database connections, and hash tables with static information. All these resources can be reallocated and re-created during the ejbActivate method.
https://docs.oracle.com/html/E13981_01/undejbs002.htm
Bare in mind the "serializing the bean to disk", note that this is oracle's implementation and it does not mean that all implementations are done this way.
I am using the Staff Library built on top of the Apache Axis2c library to implement a service, which I intend to be stateless.
As I understand it, whether a service is stateful or not (i.e. "whether the interaction of client and server involves the server keeping track of the interaction-specific data as each subsequent interaction may depend upon the outcome of the previous interaction" or not) is something that will depend on the implementation of the service architecture.
As I understand it, it is perfectly possible for me to use Staff to create a stateless service. Why then does the 'features' page of staff explicitly mention "stateful Web services implementation"? Does it even make sense for the Staff library to do that?
Maybe it's not truly stateful.
The idea why it's called "stateful" is: server stores service instances per session. Your service can store local data as class properties and you will have the same data when you working within the session.
When you log in and use sessionId provided by Login service, server will create(lazily) service instances bound to this sessionId. So for two different sessions you will have two service instances with different values of properties. This may be very useful if you working with some large objects which can't be initialized and destroyed on each call, for example the geodesic information systems.
Stateless Web service frameworks usually create service instances per client call and nothing can be stored locally, in exception you use some global mechanism like shared memory or DBMS and pass some id to distinguish one client to another.
I have a principal database (server_A), mirror database (server_B), and a witness database (server_C). The databases are set up for automatic failover, that is, when server_A goes down or fails over, server_B assumes the role of the new principal database. The database quorum is set up correctly to the best of my knowledge.
I have written an application in c++ to connect to the database and get a value to ensure a true connection. The application detects when a failure occurs on the GetValue call and attempts to reconnect when the error occurs.
The issue is this:
When I have MULTIPLE connections to the database (two threads connected, once connected, it will get a value in a loop), when the failover occurs (stopping sql server on server A so server B will take over as principal), I detect the connection failure and destroy my connection and attempt to reconnect using the same connection string:
"Driver={SQL Native Client};Server=tcp:Server_A;Failover_Partner=tcp:Server_B;Database=SomeDatabase;Uid=SomeUser;Pwd=SomePassword;"
** NOTE **
I have verified that the failover has taken place by monitoring the databases.
Even though, the connection to the database has been properly disposed of, I cannot reconnect to the database until I restart the application, OR if I bring server_A back online (now acting as the mirror database) and then failover server_B (shutting down sql server) making server A the principal database again, the application can reconnect without having to completely close out.
Though I could manipulate the connection string to make server_B the new principal and server_A the new Failover_Partner, this is not an ideal solution as many more connections will be utilized.
Keep in mind, this ONLY happens with multiple connections to the database. If I run the application with only one connection, all is fine and I can reconnect just fine when the failover occurs.
EDIT: If I connect in the beginning with multiple threads, all is fine. When I shutdown SQL Server, and therefore a failover occurs, I can reconnect only when I go through and delete ALL objects and re-instantiate new objects. Also, I am using SQL Native Client 11.0 (ODBC). Thoughts?
A lot of what you're describing is consistent with the issue described in KB 2605597 "Time-out error when a mirrored database connection is created by the .NET Framework data provider for SQLClient."
The KB describes problems when the connection timeout is set to 15 seconds, I have anecdotally heard of similar problems when the connection timeout is set to 0 (which isn't a good idea for other reasons, mentioning just in case).
This hotfix is applied to the application servers. If you want to rule this out as a possible cause, you could test raising the timeout (like it says in the workaround sections of the post) to make sure it's not the issue.
Later thought: The other thing I notice that is unusual is that you're specifying the TCP protocol in the connection string and the failover partner name. It's not clear to me from the documentation that it's supported in the failover partner name. You might want to try removing that and specifying the network attribute instead. (Recommended here.)
I do understand that you believe the issue isn't these things due to the single / multiple connections issue you've tested out.
However, I think you're better off simplifying the connection string so it's as consistent as possible with the published examples and making sure it's not the issues that people have commonly hit with this first. (The retry issue happens when there is latency, which can make it somewhat sporadic.)
Ok I have found the answer.
I had to modify the hosts file because my application did not reside in the same domain as the databases. Therefore when trying to fail over, I could not reach the database with the instance name (which is what the failover partner was cached as). I changed the hosts file to resolve the instance name to the ip address of the machine and it all works now.
I have an application interacts with Access database using DAO class, recently I converted the database to a sqlite database.
I do not know which connection method is better for the design as following:
Create only one database connection using a public variable when open the application, any queries use the only connection object for interaction during the run time, the connection is then closed when close the application
Create database connection every time before running a query, then close the database connection instantly after loading the resultset to the memory.
I recommend that you encapsulate your db access, so that the decision on whether to keep a persistent connection or not open can be changed at a later point.
Since you are using SqlLite I am assuming that it is a single user DB, so concurrency , connection contention, locking etc. are not likely to be issues.
Typically the main reasons to reuse short running connections is usually on a multi user web or service oriented system, where scalability and licensing considerations are important. This doesn't seem to be applicable in your case.
.
In short, there doesn't seem any reason not to keep a connection open for the entire duration of your app / user's login session based on the above assumptions.
If you use transactions however, I would suggest that you commit these after each successful atomic activity
You know your two options have + and -. For your special case I think to create database connection every time is not so bad idea, because creating connection to sqlite is very fast and no time consuming. Also this way you may create/close more than one connection at once, which is a good benefit, maybe you don't do it now, but in the future maybe you will have to.
Are there are any thread safety related benefits of exposing a web service as a stateless session bean?
(Correct me if i am wrong) but I think web services are not thread safe and like Servlets only one instance of a web service class is created by the server (not one instance per request).
What I don't know whether they are assigned from a pool of beans like stateless beans are - by the app server.
I am trying to find if I use #Stateless annoation with a web service that's already annotated with #WebService annotation- will that force the app server to start assigning them from a pool for each incoming request. That way I know for sure I will one separate instance created for each incoming request?
Introduction
The number of instances used by the web service endpoint depends on the framework you are using.
If you use a simple endpoint (i.e. JAX-WS with Apache CXF or Spring webservices) you will have a single service instance for all the threads/requests (as you said, Servlets). So, by definition this kind of services are meant to be stateless. But if you need to add some state to the service, you can do it, but is up to the developer to make the service thread safe.
When you use EJB you have more flexibility: if you use stateless beans you will have a pool of instances to manage all the request (if your poolSize=1 you get the same behaviour of Apache CXF). Again, you can add some state to a stateless bean, but make it thread safe is even harder because you have a pool of instances to manage. But if you need an state you can use an stateful bean to have a framework that make your life easier regarding thread safety.
Some hints regarding service states
If you do not keep an state in your service your web service is thread safe. In other words, an stateless service if thread safe by definition.
If you need some state that should be share by ALL the thread/request you can add some state to an stateless service (JAX-WS or a Stateless session bean with poolSize=1) but you need to make it thread safe, adding sycn blocks (please, do not sync your #WebMethod). IMPORTANT: In theory (and in practice), you should NEVER add an state to a stateless session bean, because the pool can destroy/create instances when it "wants to".
If you need to keep an state that will be use only by the current thread/request you can add some state to a stateless service using ThreadLocal variables, or more easily using stateful session beans.
Now, finally, answering your question
Stateless session beans are thread safe if and only if you make them thread safe: they should not have an state :-)
The only different between a classic web service and a stateless session bean web service if that the first one will have a single instance, and the second one will use a pool of instances. If your poolSize=1 you get the same effect, but in theory, the pool can destroy your instance when it "wants to".
Hoping it helps,