2

假设我打开了一个扫描仪,无论它是来自System.in文件还是来自文件,并且在我正在激活的程序中的某个时刻System.exit()(并且之前没有调用scanner.close()),它如何(以及是否)影响扫描仪?

system.exit()自从该方法关闭 JVM以来,我一直在想,与扫描仪相关的所有内容都将正确关闭,但我没有找到有关该案例的任何具体信息。例如 - 扫描仪打开的文件会在之后解锁(从扫描仪“释放”)System.exit()吗?所有被激活的相关进程是否scanner.close()也会被“激活” System.exit()

4

2 回答 2

1

Scanner 是一个流,因此当程序终止时,流会自动为您关闭,但是不关闭流是不好的做法,因为在较大的运行时间较长的程序中,它们可能会导致问题,所以是的,一切都会正确关闭,但如前所述,它是不好的做法。

如果您一次必须打开多个流,它将因 outOfMemoryError 而崩溃,这是一个示例

public static void main(String[] args) {
LinkedList<Scanner> list = new LinkedList<>();
while(true)
    list.add(new Scanner(System.in));
}

因此,如果您长时间不关闭流,则会导致此内存错误,还要注意此错误不是由于列表中的项目太多而引起的,这是由于流

编辑:

public static void main(String[] args) {
    Scanner first = new Scanner(System.in);
    Scanner second = new Scanner(System.in);
    int x = first.nextInt();
    int y = second.nextInt();
    System.out.println("First scan returns: " + x);
    System.out.println("Second scan returns: " + y);
    first.close();
    second.close();
}

如您所见,您可以打开多个 System.in 扫描仪,但是在读取变量时,您必须指定要使用的扫描仪对象。然而,这当然是毫无意义的,我想不出任何理由为什么您一次需要打开多个 System.in 扫描仪。

于 2017-05-24T20:55:58.597 回答
-1

我会这样回答你的问题。运行 java 进程的操作系统是一个编写良好且经过无限测试的软件。当一个进程退出(例如一个java进程)时,操作系统将:

  • 使 java 进程使用的内存 (RAM) 可用,即释放内存。
  • java 进程持有的文件描述符被清除。这将包括它正在读取或写入的任何文件等。
  • 等等。

But this does not mean that the best practices are not followed by the Java process. Let me give an example: imagine the java process has two threads running - one of them is updating a file and the other invokes exit. The file can become corrupted. Therefore, if this method is invoked, best practice dictates that shutdown hooks are programmed to take care of such situations. These hooks should attempt to close resources and do other kinds of housekeeping as well.

Also perhaps this will help: once System.exit() is invoked then the code proceeding to it will not be executed. So if you have a scanner.close() that will not be executed unless it is in a shutdown hook. Of course, the OS will free up the file descriptor on the process exit.

于 2017-05-24T21:38:28.890 回答