본문 바로가기
SW Programming/JAVA

(JAVA) Resources should be closed. /"close()" calls should not be redundant.

by Crystal.k 2020. 10. 5.

java static tool- SonarLint  사용하면서 만난 규칙들

 

Resources should be closed (java:S2095)

 

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

 

Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the application is on to their knees.

 

Closeable 인터페이스 또는 수퍼 인터페이스 인 AutoCloseable을 구현하는 연결, 스트림, 파일 및 기타 클래스는 사용 후 닫아야합니다. 또한 그 close 호출은 finally 블록에서 이루어져야합니다. 그렇지 않으면 예외로 인해 호출이 생성되지 않을 수 있습니다. 가급적이면 클래스가 AutoCloseable을 구현할 때 "try-with-resources"패턴을 사용하여 리소스를 생성해야하며 자동으로 닫힙니다.

 

리소스를 제대로 닫지 않으면 리소스 누수가 발생하여 애플리케이션이 먼저 표시되고 애플리케이션이 무릎을 꿇을 수 있습니다.

 

//Compiant Solution
private void readTheFile(String fileName) throws IOException {
   Path path = Paths.get(fileName);
   try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
     reader.readLine();
     // ...
   }
   // ..
   try (Stream<String> input = Files.lines("input.txt"))  {
     input.forEach(System.out::println);
   }
}


private void doSomething() {
 OutputStream stream = null;
 try {
   stream = new FileOutputStream("myfile.txt");
   for (String property : propertyList) {
     // ...
   }
 } catch (Exception e) {
   // ...
 } finally {
   stream.close();
 }
}

 

Exceptions

 

Instances of the following classes are ignored by this rule because close has no effect:

• java.io.ByteArrayOutputStream

• java.io.ByteArrayInputStream

• java.io.CharArrayReader

• java.io.CharArrayWriter

• java.io.StringReader

• java.io.StringWriter

 

Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resources statement are ignored by this rule.

//

Java 7은 Closeables를 암시 적으로 닫는 try-with-resources 문을 도입했습니다. try-with-resources 문에서 열린 모든 리소스는이 규칙에 의해 무시됩니다.

 

 

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

 //...

}

catch ( ... ) {

 //...

}

 

 

 

 

 


 

"close()" calls should not be redundant (java:S4087)

 

Java 7의 try-with-resources 구조
try 자체에서 열리는 리소스 닫기를 자동으로 처리합니다. 따라서 명시적인 close () 호출을 추가하는 것은 중복되고 잠재적으로 혼란 스러울 수 있습니다.

//Noncompliant Code Example
try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
 String contents = file.contents();
 writer.write(new Gson().toJson(new MyObject(contents)));
 writer.flush();
 writer.close();  // Noncompliant
}


// Compliant Solution
try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
 String contents = file.contents();
 writer.write(new Gson().toJson(new MyObject(contents)));
 writer.flush();
}

 

 

반응형

댓글