0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】Resource leak: 'sc' is never closed

Posted at

結論

"try-with-resources" syntaxを使う。

ワーニングが出たコード

scのところでResource leak: 'sc' is never closed
package chapter1;

import java.util.Scanner;

public class Min3 {
  static int min3(int a, int b, int c) {
    System.out.println("a: " + a + "\nb: " + b + "\nc: " + c);
    int min = a;
    System.out.println(min);
    if (min > b) min = b;
    if (min > c) min = c;
    return min;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in); // ここでエラーが出る
    int a,b,c;

    System.out.println("3つの整数のうち最小値を求めます");
    System.out.println("1つ目"); a = sc.nextInt();
    System.out.println("2つ目"); b = sc.nextInt();
    System.out.println("3つ目"); c = sc.nextInt();

    System.out.println("最小値は" + min3(a, b, c) + "です。");
  }
}


原因

Scannerが閉じられていない。

解決

tryブロックに入れる。"try-with-resources" syntaxというらしい。

java7以降
package chapter1;

import java.util.Scanner;

public class Min3 {
  static int min3(int a, int b, int c) {
    System.out.println("a: " + a + "\nb: " + b + "\nc: " + c);
    int min = a;
    System.out.println(min);
    if (min > b) min = b;
    if (min > c) min = c;
    return min;
  }

  public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in)) {
      int a,b,c;

      System.out.println("3つの整数のうち最小値を求めます");
      System.out.println("1つ目"); a = sc.nextInt();
      System.out.println("2つ目"); b = sc.nextInt();
      System.out.println("3つ目"); c = sc.nextInt();

      System.out.println("最小値は" + min3(a, b, c) + "です。");
    }
  }
}

java7以前
package chapter1;

import java.util.Scanner;

public class Min3 {
  static int min3(int a, int b, int c) {
    System.out.println("a: " + a + "\nb: " + b + "\nc: " + c);
    int min = a;
    System.out.println(min);
    if (min > b) min = b;
    if (min > c) min = c;
    return min;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    try {
      int a,b,c;
      
      System.out.println("3つの整数のうち最小値を求めます");
      System.out.println("1つ目"); a = sc.nextInt();
      System.out.println("2つ目"); b = sc.nextInt();
      System.out.println("3つ目"); c = sc.nextInt();
      
      System.out.println("最小値は" + min3(a, b, c) + "です。");
    } finally {
      sc.close();
    }
  }
}

Sytem.inの場合は閉じなくてもよい

ファイルやデータベース接続している場合は、ファイルロックやデータベース接続プールの枯渇やメモリリークの恐れがあるので確実にcloseする必要がある。

とはいっても、Scannerを使う場合は閉じないとエディタがワーニングを出してくれるので、try with resourcesを使う癖をつけていた方が無難でしょうね!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?