Can I leave SOAPConnection open forever? - java

Can I make SOAPConnection open forever? That is not calling connection.close() after soap request.

Q: Can I make SOAPConnection open forever?
A: In theory, yes.
In practice, your connection will become stale and useless the moment the other endpoint hangs up on you.
It isn't necessarily a bad strategy to:
a) open the connection initially and read whatever you need
b) simply leave the connection open
c) check for errors (which you need to do anyway)
d) close and re-open only when necessary (when an attempted read fails)
Just a thought...

there may be memory issues and as pointed out by the other user stale soap connections will be killed by routers

Are you talking about SAAJ?
The underlying TCP connection is usually cached for a specific amount of time.
Either the amount of time the server endpoint specified in the HTTP header or the amount of time JVM keeps it open.
So if the connection remains idle for too long it will be releashed.
I am not sure how long it will remain open though

You can do whatever you want do, But the best practice is something especially IO connection if you don't need use it again please close/release it, a numerous resources in memory can absolutely leak your program or even break it down.
But I am not sure whether there have a permanent principle in SOAPConnection that make a automatic closure after fixed time.

Related

Hibernate/C3P0: Is there a way to check if the connection is down in real time?

I have an application which we'll refer to as App.class that checks the database every second for real time events.
I encountered an instance where the database was down and App.class kept on retrying and throwing an exception.
What I want to achieve is to determine whether a valid connection is available or not in real time.
I can get the provider by:
C3P0ConnectionProvider provider = (C3P0ConnectionProvider) sessionFactoryImpl.getConnectionProvider()
and I could check if the connection is closed by doing: provider.getConnection().isClosed().
However, if the database is down and I try to invoke provider.getConnection(), App.class hangs for a bit (probably trying to look for a connection), then throws an exception.
I was wondering if there's an easy way to determine if a connection exists instead of just catching the error/exception when it happens.
So, c3p0 cannot tell you whether a database is "down". Metaphysically, epistemologically, it just has no access to that information. It observes only shadows of the DBMS on the walls of the network.
There are a few thing c3p0 can do for you though:
It can test Connections before giving them to you
It can not leave you hanging
You can ask it in advance whether there are likely to be Connections available without a wait.
It sounds like you have already asked c3p0 to test Connections for you on checkout, either via hibernate.c3p0.validate or c3p0.testConnectionOnCheckout. If you hadn't, you wouldn't see your app hang on getConnection() when the database was down, you'd just see failures when you tried to use the Connection. (You might be testing Connections on check-in and idle. More on that possibility below.)
Rather than putting up with a hang, you could set the config parameter c3p0.checkoutTimeout, so that if c3p0 doesn't have a good Connection to hand you relatively quickly, it sets you free with an Exception.
Ideally, you might prefer to just know in advance whether a good Connection is available before trying to check it out and hanging even briefly. You can ask c3p0 whether Connections are likely to be immediately available, via methods on c3p0's PooledDataSource interface. If you had access to a PooledDataSource pds, you'd just do something like
int idle = pds.getNumIdleConnectionsDefaultUser();
and could know whether a call to getConnection() would be likely to success quickly if there are at least a few idle Connections. (You can't have a guarantee, because c3p0 and hibernate are very asynchronous, so between your check and your checkout attempt, things may change. And no, you can't try to use a synchronized block or something to make these things atomic, c3p0's pools do their locking internally, not at the outer DataSource level.)
But even if there are idle Connections, you won't know if they are good until you test them, and if the DBMS is down, you'll hang as c3p0 tries all of its idle Connections, rejects them, and then waits in vain to try to acquire Connections. What you'd like is for c3p0 to have pre-tested the Connections, so that if none are good, none appear idle.
You can't get that perfectly, but you can come close by replacing connection testing on checkout with connection testing on checking combined with frequent tests of idle Connections. See c3p0's docs for details on how. If you do this, bad Connections will quickly be evicted from the pool, and the idle Connection count will come to approximate the count of idle good Connections. So, you'll have some, albeit imperfect, confidence that, if you see idle Connections, the DBMS is up and a call to getConnection() will succeed quickly. Back that up with a checkoutTimeout for the period when the DBMS has just crashed, but c3p0 hasn't yet detected it, and you'll be pretty close to where you want to be.
Oh, to get the PooledDataSource from a hibernate Connection provider, looking at the source code, should be something like...
import com.mchange.v2.c3p0.PooledDataSource;
PooledDataSource pds = provider.unwrap(PooledDataSource.class);
int idle = pds.getNumIdleConnectionsDefaultUser();
I haven't tried this code, and am writing this in a terrible rush (sorry!), but that should work, if it is worth this much trouble. I think most users just limit the time cost of a database outage using c3p0.checkoutTimeout without going to the trouble to get the PooledDataSource to ask about idle Connections. But if you need that, you can get it.

Java Socket Reuse

member EJP commented on my comment here, saying that you could not reuse a Socket that has had a failed connection. I have a tremendous amount of respect for EJP, however, my response is that I find this amazing... If this is true, it would seem to put a severe restriction on the lifespan of any Java app using Sockets - eventually you'd run out, right?
Can anyone clarify the situation, or point to workarounds?
I have figured this out: EJP, you are absolutely correct about this
The issue is with Socket.close() the Java Socket object cannot be reused after this, and since closing either the Input or the OutputStream is going to call close (as per the Javadocs) this is the end point for this object.
However, it seems like it is absolutely possible to create a new Socket object and bind it to the same native socket. The native socket should hopefully have been released by the Java Socket, and be available for reuse, or?
K thanks all for consideration

What happens to MySQL connection when internet connection is lost?

My application-server has a connection to a MySQL database. This connection is open 24/7.
Lets say my internet were to crash, or I were to block the port 3306.
Will JDBC throw an error? And if not, how should I be handling this kind of problem?
The reason I'm asking this is because I've had cases before where the MySQL connection randomly stopped working, but wasn't closed, which caused clients to time out.
You will get a MySQLNonTransientConnectionException or CommunicationsException. Typically, for program safety you either want to:
Open/close connections as necessary
Re-open when connection is closed
I recommend the former personally, especially when the database is user-specified (some mysql setups have a connection timeout).
Edit:
I did seem to forget to mention connection pools, per #ThorbjørnRavnAndersen , but that is also a viable solution. I personally don't do that myself, using an instantiable SQL connection per threaded operation.
Personally, I throw any database calls into try/catch blocks, because there's always the potential for issues to arise. You'll want to set some default values in the catch block, and if it happens to land on these defaults for whatever reason, display the end user some sort of (ideally pretty) error message.
Running a SQL query isn't always guaranteed to pull back any sort of results either...any number of things could go wrong - the server could be down, the connection could be so saturated that it's not able to pull the results in a timely manner, it could be sitting in the dead center of a backup of sorts too....These things have to always be accounted for, that's why I recommend doing it the way described above.
Lastly, to answer your question, yes, JDBC will in fact throw an error - under any of these circumstances.

Opening a database connection in a constructor, when should I close it?

well, I've been thinking of making database requests a little faster by keeping the connection to the database open as long as the object is being used. So I was thinking of opening the connection in the constructor of that class.
Now the question is, how can I close the connection after I stopped using? I have to call close() somewhere, don't I?
I've been reading about the finalize() method, but people seemed to be skeptical about usage of this method anywhere at all. I'd expect it to have something like a destructor, but Java doesn't have that, so?
So could anyone provide me with a solution? Thanks in advance.
I would suggest that you rather implement database connection pooling if the application would allow it. With connection pooling a pool of connections would be created and stay connected to the database. Your application would then grab a open/unused connection from the pool use it and return it to the pool.
This would allow you to acquire connections faster and you won't have to modify your classes too much. Database connection pooling is a great technique if you need to scale your application.
The other benefit is that your database connection pool will be managed by some sort of driver which will take care of opening connections, keeping them open, growing the pool if required and also shrinking the pool when extra connections are not used for a certain amount of time. This would be similar to the code you are trying to implement in the constructor and finalization methods.
Generally speaking you aqquire a database connection only when needed and release it as soon as possible.
I would recommend to make your class an implementor of java.io.Closeable. According to this interface you will have to implement void close() throws IOException, which all clients of the class will call, because it's a good practice to close Closeable classes after use.

How to force disconnection in commons-httpclient?

I use commons-httpclient to send queries to a Web server. The Web server never closes connections, but has a small memory leak associated to the connection context.
I would therefore like to close the persistent connections from time to time (every X queries for example), but I did not find any way to do this. I use the MultiThreadedHTTPConnectionManager
I could use MultiThreadedHTTPConnectionManager.closeIdleConnections(very_small_delay), but that's not very reliable: if my Java code has much work to do, then it's possible that no connection is ever idle, because there are always other threads waiting for a free connection.
Thanks,
after executing one method, let's say GET, you can read the responsed HttpStatus number, to decide if a method.releaseConnection() needs to be called.
Or if you know which connection you wanna close, you could try
MultiThreadedHTTPConnectionManager
void releaseConnection(HttpConnection conn)
okay, I thought you have some reason that you want to 'kill' a connection. Assume you have the connection, the HttpConnection Object, which you want to close in hand. May this method help?
HttpConnection
public void close()
Closes the socket and streams.
Are you calling method.releaseConnection()?
http://hc.apache.org/httpclient-3.x/threading.html#Connection_Release
Can you afford to use SimpleHttpConnectionManager(boolean alwaysClose)?
httpClient.setHttpConnectionManager(new SimpleHttpConnectionManager(true))
When I am using releaseConnections() still there are connections in CLOSE_WAIT state. Is it okay if I add closeIdleConnections(0) after releaseConnections?
Will this mean even if the connection is sent back to the pool to be used by other clients but is not closed/released then closeIdleConnections will close it?

Categories