How to use Java.sql.Connection.setNetworkTimeout?

后端 未结 2 1580
星月不相逢
星月不相逢 2021-01-05 09:47

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

相关标签:
2条回答
  • 2021-01-05 10:13

    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.

    0 讨论(0)
  • 2021-01-05 10:15

    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);
    
    0 讨论(0)
提交回复
热议问题