Automatic Resource Management

tutorial and example
tutorial and example

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources.

There are two ways of management of resources:

  1. The computer program itself manages the resource.
  2. The computer programs appoint a host to manage the resource.

Java has a resource management technique known as ARM. But before taking an insight into ARM, let us see about the garbage collection.

Garbage Collection

It is a memory management technique which frees up the memory space occupied by the objects which have not been used for a long time. It is done automatically and programmer does not have to do anything with it. Now, the question may arise as to how the JVM decides which objects to clean up? The java virtual machine has its own set of algorithms to decide which objects have not been utilized for a long period of time.

Advantages of Garbage Collection

  • Memory management is efficient
  • Requires no input from the user.

Disadvantage of Garbage Collection

  • Though the process of garbage collection manages memory but it is not instantaneous.
  • It decreases reliability.

To keep the advantages of Garbage Collection intact and overcome its disadvantages, Java 7 ARM was introduced. It was very effective for effective management of memory. ARM is used in java programs by using try with resource block and by implementing the AutoCloseable interface. This interface has only one method to be overridden by the implementing class and it is ‘close ()’. The try with resource statement is a try statement that declares one or more resources which needs to be closed at the end of methods declaration.

Scenario of closing of resources before ARM was introduced.

Before Java 7 the resources were closed using the try and finally statements. It is illustrated with the help of program written below:

The close method was called under the finally block and the resources were closed.

With ARM let us see the scenario

With ARM being used, the resources get automatically closed at the end of the try block.

What happens if we have more than two resources?

We can do this by increasing the level of nesting, that is we can enclose the second resource try block in the first one or vice versa. But it can make the code noisy. To avoid such issues, we declare both the resources in the same try block as illustrated in program below:

We can do this for multiple resources as well. So ARM provides a measure of effective resource management for one as well as more than one resources.

Benefits of ARM:

  • It takes place instantaneously.
  • More than one resources can also be used simultaneously.
  • It is less noisy.