Java应用程序终止使用时是否释放了资源? [英] Are resources used by a Java application freed when it terminates?

查看:217
本文介绍了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.

请注意,第三个要点是相当普通的事情:大多数操作系统都将处理此问题,并且它与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.

另请参阅:

  • 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

这篇关于Java应用程序终止使用时是否释放了资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆