Show TOC Start of Content Area

Background documentation Resource Management  Locate the document in its SAP Library structure

Operating system resources like network connections, file handles or database connections are a limited resource. Therefore it is more than good etiquette to release resources as soon as possible. A common misperception is that the garbage collection will take care of that. While this might be true for a single user system with a lot of spare CPU time, the situation in a server environment is much more different.

Recommendation

Release limited resources as soon as possible.

Resources with limited availability should be released as soon as possible and in a reliable way, like calling the release method (for example, close) of the resource from inside a finally block. This block has to be declared even when there are no checked exceptions (no try clause).

 

Because of the high work load typical for application servers, it is more likely that it will take some time for the garbage collector to finalize an object with a resource. The resource is unavailable because to the latency of the garbage collector.

To avoid this situation, all classes that encapsulate limited resources offer methods to release them early.

     InputStream is = socket.getInputStream();
     …   
// read the file
     
is.close();  // release resources early

 

While this example works fine for local files it does not handle failures.

Example:

The variable is could also point to a network connection that might be interrupted any time - causing an exception. Even when exceptions occur, our resource should still be released before it is discovered by the garbage collector.

     InputStream is = null;
     
try {
        is = socket.getInputStream();
        … 
// read the file
     
catch(IOException ex) {
        …   
     
// important
     } finally {
        
if(is != null) {
         is.close();
        }
     }

 

End of Content Area