If the a program relies on finalize()
to release system resources, or if there is confusion over which part of the program is responsible for releasing system resources, then there exists a possibility for a potential resource leak. In a busy system, there might be a time gap before the finalize()
method is called for an object. An attacker might exploit this vulnerability to induce a denial-of-service attack. Rule OBJ02-J has more information on the usage of finalizers.
If there is unreleased memory, eventually the Java garbage collector will be called to free memory; however. However, if the program relies on nonmemory resources like file descriptors and database connections, unreleased resources might lead the program to prematurely exhaust its pool of resources. In addition, if the program uses resources like Lock
or Semaphore
, waiting for finalize()
to release the resources may lead to resource starvation.
...
However, while being slightly better, this code is also non-compliantnoncompliant. Both rs
and stmt
might be null.
...
Again, while being still better, the code is still non-compliantnoncompliant. This is because rs.close()
might itself result in a SQLException
, and so stmt.close()
will never be called.
...
Noncompliant Code Example
The worst form of non-compliance noncompliance is not calling methods to release the resource at all. If files are opened, they must be explicitly closed when their work is done.
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName) throws IOException, FileNotFoundException { FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = new BufferedReader(stream); String line; while((line=bufRead.readLine())!=null) { sendLine(line); } return 1; } |
Compliant Code Example
A This compliant code example would release all acquired resources, regardless of any exceptions which might occur. Hence, in the compliant code below, even though bufRead
might result in an exception, if a FileInputStream
object was instantiated, it will be closed.
Code Block | ||
---|---|---|
| ||
FileInputStream stream = null; BufferedReader bufRead = null; String line; try { stream = new FileInputStream(fileName); bufFread = new BufferedReader(stream); while((line=bufRead.readLine())!=null) { sendLine(line); } } catch (IOException e) { } catch {FileNotFoundException e) { } finally { stream.close(); } |
Risk Assessment
Acquiring non-memory nonmemory system resources and not releasing them explicitly might lead to resource exhaustion.
...