14 Replies Latest reply: Apr 15, 2012 11:33 AM by 929204 RSS

    Garbage collection and what happens to resources when a program ends

    929204
      Hello everyone,
      Could someone tell me what happens to resources when a program ends?
      Are resources such as a "java.sql.Connection" or a "java.nio.channels.WritableByteChannel" automatically closed when an application ends?

      Also, is there some kind of garbage collection that takes place? According to Effective Java 2nd edition item 7, "It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable." What happens, then?

      Thanks in advance!

      Edited by: Jujubi on Apr 12, 2012 10:36 AM
        • 1. Re: Garbage collection and what happens to resources when a program ends
          tschodt
          Jujubi wrote:
          Could someone tell me what happens to resources when a program ends?
          Are resources such as
          a "java.sql.Connection"
          The underlying socket will be cleared by the TCP/IP stack,
          maybe not immediately
          or a "java.nio.channels.WritableByteChannel" automatically closed when an application ends?
          All the memory that was used by the Java VM is reclaimed by the operating system.
          Also, is there some kind of garbage collection that takes place? According to Effective Java 2nd edition item 7, "It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable." What happens, then?
          Depends what kind of resources you are talking about.
          • 2. Re: Garbage collection and what happens to resources when a program ends
            DrClap
            For example: an un-closed FileOutputStream will be abandoned when the application ends. Closing the stream would write out any unwritten but buffered data; however that doesn't happen when the application ends without explicitly closing the stream. Likewise for database connections: they aren't explicitly closed by application termination, so the database server retains a dead connection until such time as it happens to notice that.
            • 3. Re: Garbage collection and what happens to resources when a program ends
              EJP
              The underlying socket will be cleared by the TCP/IP stack,
              maybe not immediately
              Immediately. The port may linger in TIME_WAIT state for 2 minutes after that.
              or a "java.nio.channels.WritableByteChannel" automatically closed when an application ends?
              Yes.
              Also, is there some kind of garbage collection that takes place?
              No.
              According to Effective Java 2nd edition item 7, "It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable." What happens, then?
              Nothing. The finalizers aren't executed. However as finalizers generally only contain closes for things that the OS will close anyway it doesn't matter. Never seen a case where it matters in 15 years of Java.
              • 4. Re: Garbage collection and what happens to resources when a program ends
                929204
                Thank you everyone for your replies.
                Is it safe to say that it's good practice to clean up after yourself and close any open connections/resources if you know that the program is about to terminate, regardless of what the JVM will do with such resources if you were to neglect to manually close them?
                • 5. Re: Garbage collection and what happens to resources when a program ends
                  EJP
                  As stated above, you must always closed any buffered output stream or writer yourself, otherwise you will lose data. You must close database connections yourself, otherwise you will get either a commit or an abort depending on the vendor, and you mightn't therefore get the one you want. (You should be closing DBMS connections inside finally blocks actually, and using a connection pool, not holding on to them forever.)

                  There are some resources you don't need to clean up: you don't need to dispose of Swing windows, for example, and you don't need to, and can't, dispose of MappedByteBuffers.
                  • 6. Re: Garbage collection and what happens to resources when a program ends
                    929204
                    EJP wrote:
                    (You should be closing DBMS connections inside finally blocks actually, and using a connection pool, not holding on to them forever.)
                    May I ask why? I'm especially curious because presently I'm writing an app that queries a database. I have the database connection encapsulated in a singleton. It opens up a connection to the database and then basically holds on to that connection until it is explicitly told to close it. (I've been trying to design the program so that the database object is always told to close before the program terminates.)
                    • 7. Re: Garbage collection and what happens to resources when a program ends
                      EJP
                      May I ask why?
                      Because it is easier to program than using a long-lived connection, and more efficient than using lots of short-lived ones, so you get the best of both worlds. Easier because you can just manage the connection as a local object in a method, closed in a finally {} block, and more efficient because the real connection costs can be amortized.
                      • 8. Re: Likewise for database connections
                        BIJ001
                        Likewise for database connections: they aren't explicitly closed by application termination,
                        so the database server retains a dead connection until such time as it happens to notice that.
                        Well, the operating system will dispose of the resources held by the process (whether the Java engine or other) on its termination. The OS-managed resources include the open file descriptors (handles), pipes, sockets etc. So if the database connection is through a socket, the underlying socket will be closed by the OS upon the termination of the process, and the socket's other end being closed might be detected by the database sever.

                        Having said that, it is a good idea to dispose of the unnecessary resources in the program as soon as possible.
                        • 9. Re: Garbage collection and what happens to resources when a program ends
                          aksarben
                          Ditto what the other replies say. In the larger scheme of things, connection pooling is a good idea for more than just databases. Any time you connect to an external entity (database, JMS server, middleware, etc.), the other end is likely to be unaware that your app has exited, crashed, etc. So--depending how the "other end" is configured--it may try to keep the connection open indefinitely, which in extreme cases can lead to resource exhaustion, memory leaks, etc.
                          • 10. Re: Garbage collection and what happens to resources when a program ends
                            jschellSomeoneStoleMyAlias
                            aksarben wrote:
                            In the larger scheme of things, connection pooling is a good idea for more than just databases. Any time you connect to an external entity (database, JMS server, middleware, etc.), the other end is likely to be unaware that your app has exited, crashed, etc. So--depending how the "other end" is configured--it may try to keep the connection open indefinitely, which in extreme cases can lead to resource exhaustion, memory leaks, etc.
                            Huh?

                            If an app is using a connection pool versus connections on demand then if the app crashes then the other end will have all of the existing pooled connections still in use. A connection pool doesn't solve any problems in that scenario.
                            • 11. Re: Garbage collection and what happens to resources when a program ends
                              jschellSomeoneStoleMyAlias
                              Jujubi wrote:
                              EJP wrote:
                              (You should be closing DBMS connections inside finally blocks actually, and using a connection pool, not holding on to them forever.)
                              May I ask why? I'm especially curious because presently I'm writing an app that queries a database. I have the database connection encapsulated in a singleton. It opens up a connection to the database and then basically holds on to that connection until it is explicitly told to close it. (I've been trying to design the program so that the database object is always told to close before the program terminates.)
                              Err...I doubt that is valid.

                              If you have something like a client user app that uses connections on a fairly infrequent basis on behalf of a human and every thing else is normal then there is no point in just not opening and closing the connection every time.

                              For a normal client app that a human is using a connection pool is at best going to have limited usage and one MUST configure it appropriately for such a usage. Otherwise one can end up with situations where every client app is using 10-100 connections all the time when 1 is more than enough.

                              If you have a server application which is going to be experiencing low traffic then the same thing can apply. That said you might use a connection pool if you want to learn how to use it.

                              For a high volume server it is possible but not guaranteed, presuming a modern data center, that one might get a better tps (transaction per second) measurement by using a pool. However that is not a zero cost option because in such a scenario it the server must be designed with consideration for what happens with stale connections and normal expected failure scenarios that might show up with a pool. (Similar problems can show up without a pool but are much less likely to show up given normal randomness and will be more obvious when they do.)
                              • 12. Re: Garbage collection and what happens to resources when a program ends
                                796440
                                @OP: So, just so you're clear on this, there are two main aspects to this cleanup:

                                1) The cleanup that affects your application and its data.

                                2) The cleanup that affects system resources that your application has been using.

                                For #1, if you don't properly close(), commit(), etc., then you will probably lose data. A file will be partially written, a database transaction will be rolled back, etc. You need to handle this explicitly, usually in a finally block. Note that this applies only (or, if I missed something, then "mostly") to I/O operations.

                                For #2 any resources that your app was using--memory, file handles, sockets, DB connections, etc.--will be returned to the system, though in some cases there will be a delay before they can be used by other apps.

                                So, yes, you should always properly clean up after yourself, but if you don't, it's only your own app's data that will suffer lasting damage.
                                • 13. Re: Garbage collection and what happens to resources when a program ends
                                  929204
                                  jschell wrote:
                                  If you have something like a client user app that uses connections on a fairly infrequent basis on behalf of a human and every thing else is normal then there is no point in just not opening and closing the connection every time.
                                  Thanks for your informative message. My application fits the above description. I'll change it so that whenever the user needs to query the DB, a connection is opened (and closed) in a try block with resources.
                                  • 14. Re: Garbage collection and what happens to resources when a program ends
                                    929204
                                    jverd wrote:
                                    @OP: So, just so you're clear on this, there are two main aspects to this cleanup:

                                    1) The cleanup that affects your application and its data.

                                    2) The cleanup that affects system resources that your application has been using.

                                    For #1, if you don't properly close(), commit(), etc., then you will probably lose data. A file will be partially written, a database transaction will be rolled back, etc. You need to handle this explicitly, usually in a finally block. Note that this applies only (or, if I missed something, then "mostly") to I/O operations.

                                    For #2 any resources that your app was using--memory, file handles, sockets, DB connections, etc.--will be returned to the system, though in some cases there will be a delay before they can be used by other apps.

                                    So, yes, you should always properly clean up after yourself, but if you don't, it's only your own app's data that will suffer lasting damage.
                                    Thank you; your post helped me to clear up various points that have been mentioned in this thread.