简体   繁体   English

JDBC 未关闭的连接

[英]JDBC unclosed connections

If we forget to close Java JDBC connection (say oracle) in the code , would like to know will the connection stays at DB end forever (oracle) or the Oracle has any implementation at its end to auto release DB connections after some time?如果我们忘记在代码中关闭 Java JDBC 连接(比如 oracle),想知道连接会永远停留在 DB 端(oracle)还是 Oracle 在其末端有任何实现在一段时间后自动释放 DB 连接?

try{
       ds.getConnection();
       //do some business logic

   }catch(Exception e){
       //handle exceptions

   }  finally{
           //let's say DB connection is NOT cosed..
      }

What happens to the open connection in the code above?上面代码中打开的连接会发生什么? Does the connection gets auto released at database side once the java program exits? java程序退出后,连接是否会在数据库端自动释放? I understand it is highly not recommended and bad practice to not close DB connections.我知道不关闭数据库连接是非常不推荐和不好的做法。 I just want to know the implications and understand how oracle handles unclosed connections.我只想知道其中的含义并了解 oracle 如何处理未关闭的连接。

Once the VM is terminated, whether more or less normally (all non-daemon threads end, System.exit is invoked, or a kill signal is received, such as hitting CTRL+C in the terminal), or abnormally (you trip over a powercord, or a terminate signal causes the kernel to just hard-exit your VM), all TCP/IP connections go away automatically, and with that, the connection is cleaned up.一旦 VM 终止,无论是正常情况(所有非守护线程结束,调用 System.exit,或接收到终止信号,例如在终端中按 CTRL+C),还是异常(您绊倒一个电源线或终止信号会导致内核硬退出您的虚拟机),所有 TCP/IP 连接都会自动消失,并且连接将被清除。

But, until the VM exits, you get no guarantees.但是,在 VM 退出之前,您无法获得任何保证。 The behaviour is intentionally unspecified (as in, you must close them yourself. If you do not, no guarantees are provided), and what actually happens depends on the state of your computer (as it depends on gc runs and when those go depends on everything from which song is playing in your music player to the phase of the moon), and the JDBC driver being used.该行为是故意未指定的(例如,您必须自己关闭它们。如果您不这样做,则不提供任何保证),实际发生的情况取决于您的计算机状态(因为它取决于 gc 运行以及何时关闭取决于从音乐播放器中播放的歌曲到月相的所有内容),以及正在使用的 JDBC 驱动程序。

You can use lint tools and IDE plugins to recognize that you aren't closing your connections.您可以使用 lint 工具和 IDE 插件来识别您没有关闭连接。 Also, your snippet is over 10 years out of date.此外,您的代码段已过期 10 多年。 The recommended and much simpler way to ensure your connection does not die on you is to use:确保您的连接不会死在您身上的推荐且更简单的方法是使用:

try (Connection con = ds.getConnection()) {
    // use 'con' here
} // no need for a catch or finally.

Or, use connection poolers (like HikariCP), along with an abstraction to make JDBC less annoying, such as JDBI or JOOQ.或者,使用连接池(如 HikariCP),以及使 JDBC 不那么烦人的抽象,如 JDBI 或 JOOQ。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM