Improper Resource Release
Improper Resource Release
Overview
Improper resource release occurs when files, streams, sockets, database connections, or locks are not closed.
Impact
Leaked resources can exhaust memory, handles, connections, or locks and reduce availability.
Countermeasures
Use structured cleanup such as try-with-resources or finally blocks and verify cleanup on both success and failure paths.
Examples
try {
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(file);
FileCopyUtils.copy(fis, os);
fis.close();
return true;
} catch (IOException e) {
logger.error(e, e);
}
OutputStream os = null;
FileInputStream fis = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, os);
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
fis.close();
os.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
OutputStream os = null;
FileInputStream fis = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, os);
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
if (fis =! null)
fis.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
try {
if (os =! null)
os.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}