Java 应用程序终止时使用的资源是否被释放?

2022-01-24 00:00:00 connection memory-management java

Java 应用程序可能使用在不再需要时应关闭的 IO 流、套接字或数据库连接.

Java applications may use IO streams, sockets or database connections that should be closed when they are no longer needed.

但是,应用程序可能会被终止(例如通过终止进程).在这种情况下是否会释放所有使用的资源?谁来释放它们:OS 还是 JRE?

However, applications may be terminated (e.g. by killing the process). Will all used resources be freed in this case? Who will free them: OS or JRE?

推荐答案

如果你的软件没有做好资源管理,会出现以下情况:

If your software doesn't take care of resource management properly, the following will happen:

  • 在运行时:JVM 将在您的程序执行期间尝试关闭打开的流(如果它们看似未使用)(在垃圾收集周期期间),
  • 在程序的终止点:JVM 应关闭由您的程序打开的所有类型的打开流,
  • 在 JVM 的进程终止点:操作系统将负责释放 JVM 未正确释放的任何内容(希望如此,否则该操作系统存在一些严重问题...).
  • at runtime: the JVM will attempt during the duration of your program to close open streams if they're are seemingly unused (during garbage collection cycles),
  • at your program's termination point: the JVM should close open streams of all kinds left open by your program,
  • at the JVM's process termination point: the operating system will take care of releasing anything that hasn't been properly released by the JVM when it exists (hopefully, or this OS has some serious issues...).

正如 Vulcan 所说,显然,这些都不能确保它们在另一端得到妥善处理.

As mentioned by Vulcan, none of this ensures that they are properly dealt with on the other end, obviously.

请注意,第 3 个要点是一个相当通用的内容:大多数操作系统都会处理这一点,并且它与 Java 平台的内部结构无关.它是关于操作系统自行管理其进程和资源.

Note that the 3rd bullet point is a rather generic thing: most operating systems will take care of this, and it doesn't relate to the Java Platform's internals. It's about the OS managing its processes and resources on its own.

另见:

  • 在异常退出时清理资源,也在 StackOverflow 上
  • 如何在 Java 中实现优雅终止
  • Java 理论与实践:良好的内务管理实践,在 IBM 开发人员系列中
  • Cleanup of resources on an abnormal Exit, also on StackOverflow
  • How do I implement graceful termination in Java
  • Java Theory and Practice: Good Housekeeping Practices, at the IBM Developer Series

相关文章