不適切なリソース解放

不適切なリソース解放

概要

不適切なリソース解放は、ファイル、ストリーム、ソケット、DB接続、ロックが閉じられないと発生します。

影響

リソース漏れはメモリ、ハンドル、接続、ロックを枯渇させ、可用性を低下させます。

対策

try-with-resourcesやfinallyブロックなどの構造化された解放を使い、成功時と失敗時の両方で解放されることを確認します。

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());
    }    
}