End Java command line application properly

旧巷老猫 提交于 2019-12-08 16:31:00

问题


I am just wondering. Do I need to call System.exit(0); right before main method of a Java command line application ends? If so, why? What is the difference from letting it exit on its own, if I would just always put there 0? What is not cleaned up?

Thanks in advance.


回答1:


No! You do not always need to call System.exit(0) to end a java program. If there is no non-daemon thread spawned by your code, the application will terminate automatically upon finishing your main thread task.

If your main method results in spawning some non-daemon thread which are still alive doing some processing while your main method has reached the end, then the application will not be terminated until those threads complete. In this case, if you explicitly call System.exit(0), then application will terminate immediately killing all your threads.

Please refer javadoc of Thread which mentions the details.




回答2:


No need to call System.exit(), just return from main(). This is the normal idiom for exiting from a Java program.

System.exit() is usually called to terminate an app in the middle of things (which usually means abnormal termination due to a fatal error).



来源:https://stackoverflow.com/questions/3733890/end-java-command-line-application-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!