Are resources used by a Java application freed when it terminates?

前端 未结 2 1281
礼貌的吻别
礼貌的吻别 2021-01-22 22:38

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

However, applications may be terminated (e.g.

2条回答
  •  迷失自我
    2021-01-22 23:03

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

    • 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...).

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

    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.

    More Info

    See also:

    • 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

提交回复
热议问题