programing

리소스 누출 : 'in'은 닫히지 않습니다.

nasanasas 2020. 10. 19. 08:08
반응형

리소스 누출 : 'in'은 닫히지 않습니다.


Eclipse가 다음 코드에서 "Resource leak : 'in'is never closed"라는 온난화를주는 이유는 무엇입니까?

public void readShapeData() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the width of the Rectangle: ");
        width = in.nextDouble();
        System.out.println("Enter the height of the Rectangle: ");
        height = in.nextDouble();

스캐너를 닫지 않기 때문에

in.close();

다른 사람들이 말했듯이 IO 클래스에서 'close'를 호출해야합니다. 다음과 같이 try-finally 블록을 캐치없이 사용할 수있는 훌륭한 장소라고 추가하겠습니다.

public void readShapeData() throws IOException {
    Scanner in = new Scanner(System.in);
    try {
        System.out.println("Enter the width of the Rectangle: ");
        width = in.nextDouble();
        System.out.println("Enter the height of the Rectangle: ");
        height = in.nextDouble();
    } finally {
        in.close();
    }
}

이렇게하면 스캐너가 항상 닫히고 적절한 리소스 정리가 보장됩니다.

마찬가지로 Java 7 이상에서는 "try-with-resources"구문을 사용할 수 있습니다.

try (Scanner in = new Scanner(System.in)) {
    ... 
}

그것이 발생하는지 확인하기 위해 블록 in.close()에서 호출해야 finally합니다.

이클립스 문서에서, 여기에 그 깃발이 특정 문제 ( 강조 광산) :

인터페이스 java.io.Closeable (JDK 1.5 이후) 및 java.lang.AutoCloseable (JDK 1.7 이후 )을 구현하는 클래스 는 더 이상 필요하지 않을 때 close () 메소드를 사용하여 닫아야하는 외부 자원을 나타내는 것으로 간주됩니다.

Eclipse Java 컴파일러는 이러한 유형을 사용하는 코드가이 정책을 준수하는지 여부를 분석 할 수 있습니다.

...

컴파일러는 "Resource leak : 'stream'is never closed"로 [위반] 플래그를 지정합니다.

여기에 자세한 설명이 있습니다 .


를 사용하여 인스턴스화 한 스캐너를 닫아야한다는 메시지 System.in입니다 Scanner.close(). 일반적으로 모든 독자를 닫아야합니다.

을 닫으면 System.in다시 읽을 수 없습니다. Console수업을 살펴볼 수도 있습니다 .

public void readShapeData() {
    Console console = System.console();
    double width = Double.parseDouble(console.readLine("Enter the width of the Rectangle: "));
    double height = Double.parseDouble(console.readLine("Enter the height of the Rectangle: "));
    ...
}

JDK7 또는 8을 사용하는 경우 리소스와 함께 try-catch를 사용할 수 있습니다. 그러면 자동으로 스캐너가 닫힙니다.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

당신은해야 닫고 당신이 그것을 완료하면 스캐너를 :

in.close();

일반적으로 I / O를 처리하는 클래스의 인스턴스는 작업을 마친 후에 닫아야합니다. 따라서 코드 끝에 in.close().


private static Scanner in;

개인 정적 스캐너 클래스 변수로 선언하여 수정했습니다. 그것이 왜 고쳐 졌는지 확실하지 않지만 그것이 내가 권장하는 일입니다.


adding private static Scanner in; does not really fix the problem, it only clears out the warning. Making the scanner static means it remains open forever (or until the class get's unloaded, which nearly is "forever"). The compiler gives you no warning any more, since you told him "keep it open forever". But that is not what you really wanted to, since you should close resources as soon as you don't need them any more.

HTH, Manfred.


// An InputStream which is typically connected to keyboard input of console programs

Scanner in= new Scanner(System.in);

above line will invoke Constructor of Scanner class with argument System.in, and will return a reference to newly constructed object.

It is connected to a Input Stream that is connected to Keyboard, so now at run-time you can take user input to do required operation.

//Write piece of code 

To remove the memory leak -

in.close();//write at end of code.

The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.


Scanner sc = new Scanner(System.in);

//do stuff with sc

sc.close();//write at end of code.

in.close();
scannerObject.close(); 

It will close Scanner and shut the warning.

참고URL : https://stackoverflow.com/questions/12519335/resource-leak-in-is-never-closed

반응형