Search code examples
javamultithreadingsecuritymanager

If the current thread has the authority to exit Java virtual machine


I'm trying the class SecurityManager. I want to check if the current thread has the authority to exit Java virtual machine. Below is the code I came up with.

SecurityManager appsm = System.getSecurityManager();
System.out.println("something");
appsm.checkExit(0);

I was expecting the SecurityManager.checkExit to throw a SecurityException. However, the IDE instead output NullPointerException.

Exception in thread "main" java.lang.NullPointerException
    at jtotheplatformenvironment.JTOThePlatformEnvironment.main(JTOThePlatformEnvironment.java:40)
C:\Users\Justin\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

Why is this happening?


Solution

  • You need to execute the Java application with an extra parameter :

    -Djava.security.manager
    

    So the JVM would be started with a built-in default security manager (source) otherwise no security manager is created and that's why you get a NPE.