资源泄漏“空白”从未关闭

时间:2013-10-19 18:39:54

标签: java java.util.scanner resource-leak

似乎在我创建扫描仪时出现此错误。我试图通过搜索错误名称来解决这个问题,但到目前为止还没有成功地让消息停止显示。

代码:

import java.util.Scanner;
public class PrintQueue {
    //Instance variables
    private Queue<Job> pq;
    //Constructor
    public PrintQueue() {
        pq = new Queue<Job>();
    }
    //Adds a job object to the end of the queue
    public void lpr(String owner, int jobId) {
        Job j = new Job(owner, jobId);
        pq.enqueue(j);
    }
    //Enumerates the queue
    public void lpq() {
        Job curr = pq.first();
        for (int i = 0; i < pq.size(); i++) {
            System.out.println(curr);
            curr = pq.next();
        }
    }
    //Removes the first entry in the queue if the input integer matches the integer contained within the job object
    public void lprm(int jobId) {
        if (pq.first().getJobId() == (jobId))
            pq.dequeue();
        else 
            System.out.println("Unable to find jobId.");
    }
    //Removes all objects that contain the input String
    public void lprmAll(String owner) {
        Job curr = pq.first();
        for (int i = 0; i < pq.size(); i++) {
            if (curr.getOwner().equals(owner)) 
                pq.dequeue();
            curr = pq.next();
        }
    }
    //Demo 
    public static void main(String[] args) {
        Scanner k = new Scanner(System.in);
        PrintQueue myPQ = new PrintQueue();
        String name;
        int id;
        for (int i = 1; i <= 5; i++) {
            System.out.print("Enter owner and id: ");
            name = k.next();
            id = k.nextInt();
            myPQ.lpr(name, id);
        }
        System.out.println("Print Queue");
        myPQ.lpq();
        myPQ.lprm(101);
        myPQ.lprmAll("ronaldinho");
        System.out.println("Print Queue"); 
        System.out.println("\n\n"); 
        myPQ.lpq(); 
    }
}

我收到错误的部分:

Scanner k = new Scanner(System.in);

2 个答案:

答案 0 :(得分:1)

那是因为你永远不会关闭Scanner。将您的代码更改为:

Scanner k = null;
try {
    k = new Scanner(System.in);
    //do stuff with k here...
} finally {
    if( k != null )
        k.close();
}

答案 1 :(得分:0)

似乎警告而不是错误。然而,解决它是一个好习惯。

实际上,您只需在方法的最后调用k.close();即可。 最佳做法是在finally块中调用close:这可以保证在抛出异常时资源被关闭;

Scanner k = null;
try {
    k = new Scanner(System.in);
    ........
} finally {
    if (k != null) {
        k.close();
    }
}

幸运的是,java 7提供的语法不那么冗长:

try (
    Scanner k = new Scanner(System.in);
) {
    .... // use k
} 

当在Closable块的特殊部分中创建实现try的任何类的对象时,使用常规括号()标记,您不必编写finally块:它是由编译器添加的。