Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java.sql.Connection.setNetworkTimeout?

I ran into the exact issue that setNetworkTimeout is supposed to solve according to Oracle. A query got stuck in socket.read() for several minutes.

But I have little idea what the first parameter for this method needs to be. Submitting a null causes an AbstractMethodError exception, so... does the implementation actually need some sort of thread pool just to set a network timeout?

Is there some way to achieve the same effect without running a thread pool just for this one condition?

like image 246
Kristaps Baumanis Avatar asked May 18 '12 14:05

Kristaps Baumanis


2 Answers

It seems like the documentation explains this horribly, but without looking at any code behind the class my guess would be that you are expected to pass an Executor instance to the method so that implementations can spawn jobs/threads in order to check on the status of the connection.

Since connection reads will block, in order to implement any sort of timeout logic it's necessary to have another thread besides the reading one which can check on the status of the connection.

It sounds like a design decision was made that instead of the JDBC driver implementing the logic internally, of how/when to spawn threads to handle this, the API wants you as the client to pass in an Executor that will be used to check on the timeouts. This way you as the client can control things like how often the check executes, preventing it from spawning more threads in your container than you like, etc.

If you don't already have an Executor instance around you can just create a default one:

conn.setNetworkTimeout(Executors.newFixedThreadPool(numThreads), yourTimeout);
like image 136
matt b Avatar answered Nov 16 '22 21:11

matt b


As far as Postgres JDBC driver is concerned (postgresql-42.2.2.jar), the setNetworkTimeout implementation does not make use of the Executor parameter. It simply sets the specified timeout as the underlying socket's timeout using the Socket.setSoTimeout method.

It looks like the java.sql.Connection interface is trying not to make any assumptions about the implementation and provides for an executor that may be used if the implementation needs it.

like image 1
Nanda Avatar answered Nov 16 '22 22:11

Nanda