Sometimes I receive the
java.net.SocketException: Too many open files
java.net.Socket.createImpl(Socket.java:397)
java.net.Socket.connect(Socket.java:527)
org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:123)
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:597)
I saw the similar question java.net.SocketException: Too many open files, and I use apache's httpclient too, but it seems answers was not quite helpful for me...
There was two answers:
1) doing httpClient.getConnectionManager().shutdown();
2) call entity.getContent().close()
instead of entity.consumeContent()
But seems none of them is suitable...
1) The problem is that I'm using ThreadSafeConnectionManager
. It is created once (on the application startup). and therefore we do not making shutdown (so that connections are reusable). If I do shutdown on this manager - all the connection will be closed. It would be appropriate if I use SingleClientConnectionManager
, but I don't. Am I right?
2) I found out that I don't close the stream too. But when I started to debug - it appears that this getContent()
stream is already closed, even before calling the consumeContent()
. Although (even after consumeContent
) the socketInputStream
inside those getContent() stream was not closed, as well as socket. Is it bad? Can it be the cause of the problem? And I didn't find the way how to close this socket! It's located very inside the outer input stream, so I can't get it. But I see in the debug mode, that this socket is not closed, as well as SocketInputStream
.
How normally we should work with a ThreadSafeConnectionManager
- should it be created only once? and if it is so, how to properly close those sockets if any?