How to use Java.sql.Connection.setNetworkTimeout?

I ran into the exact problem setNetworkTimeout has to solve according to Oracle . Request stuck in socket.read () for several minutes.

But I have no idea what the first parameter for this method should be. Sending a null value throws an AbstractMethodError exception, so ... does the implementation really need some kind of thread pool to set the network timeout?

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

+3
source share
2 answers

The documentation seems to explain this terribly, but without looking at any code behind the class, I assume that you should pass an instance of Executor to the method so that implementations can spawn jobs / threads to check connection status.

Since the connection reading is blocked, to implement any timeout logic, it is necessary to have one more stream, besides reading, which can check the connection status.

It seems that a constructive decision was made that instead of a JDBC driver that implements internal logic, about how / when to spawn threads to handle this, the API wants you, as a client, to go through the Executor, which will be used to check timeouts. This way, you, as a client, can control such things as checking is often performed, not allowing it to create more threads in your container than you like, etc.

If you do not already have an instance of Executor, you can simply create it by default:

conn.setNetworkTimeout(Executors.newFixedThreadPool(numThreads), yourTimeout); 
+9
source

As for the Postgres JDBC driver (postgresql-42.2.2.jar), the setNetworkTimeout implementation does not use the Executor parameter. It simply sets the specified timeout as the main socket timeout using the setSoTimeout method.

It seems that the java.sql.Connection interface tries not to make any assumptions about the implementation and provides an executor that can be used if the implementation needs it.

0
source

Source: https://habr.com/ru/post/917627/


All Articles