Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Potential input resource leak

ID: java/input-resource-leakKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - performance   - efficiency   - resources   - external/cwe/cwe-404   - external/cwe/cwe-772Query suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A subclass ofReader orInputStream that is opened for reading but not closed may cause a resource leak.

Recommendation

Ensure that the resource is always closed to avoid a resource leak. Note that, because of exceptions, it is safest to close a resource in afinally block. (However, this is unnecessary for subclasses ofCharArrayReader,StringReader andByteArrayInputStream.)

For Java 7 or later, the recommended way to close resources that implementjava.lang.AutoCloseable is to declare them within atry-with-resources statement, so that they are closed implicitly.

Example

In the following example, the resourcebr is opened but not closed.

publicclassCloseReader{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbr=newBufferedReader(newFileReader("C:\\test.txt"));System.out.println(br.readLine());// ...}}

In the following example, the resourcebr is opened in atry block and later closed in afinally block.

publicclassCloseReaderFix{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbr=null;try{br=newBufferedReader(newFileReader("C:\\test.txt"));System.out.println(br.readLine());}finally{if(br!=null)br.close();// 'br' is closed}// ...}}

Note that nested class instance creation expressions ofReaders orInputStreams are not safe to use if the constructor of the outer expression may throw an exception. In the following example, theInputStreamReader may throw an exception, in which case the innerFileInputStream is not closed.

publicclassCloseReaderNested{publicstaticvoidmain(String[]args)throwsIOException{InputStreamReaderreader=null;try{// InputStreamReader may throw an exception, in which case the ...reader=newInputStreamReader(// ... FileInputStream is not closed by the finally blocknewFileInputStream("C:\\test.txt"),"UTF-8");System.out.println(reader.read());}finally{if(reader!=null)reader.close();}}}

In this case, the inner expression needs to be assigned to a local variable and closed separately, as shown below.

publicclassCloseReaderNestedFix{publicstaticvoidmain(String[]args)throwsIOException{FileInputStreamfis=null;InputStreamReaderreader=null;try{fis=newFileInputStream("C:\\test.txt");reader=newInputStreamReader(fis);System.out.println(reader.read());}finally{if(reader!=null)reader.close();// 'reader' is closedif(fis!=null)fis.close();// 'fis' is closed}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp