3

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?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • 1
    java does not run with a SecurityManager by default, therefore you are getting an NPE. you have to start your program with the SecurityManager enabled. – jtahlborn Mar 01 '16 at 03:19
  • @Thank you very much for the suggestion! How can I enable SecurityManager at start of my program? –  Mar 01 '16 at 03:28

2 Answers2

2

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.

Benoit Vanalderweireldt
  • 2,925
  • 2
  • 21
  • 31
0

As per oracle documentation, you can set SecurityManager by using below API in System class

public static void setSecurityManager(SecurityManager s)

Sets the System security.

If there is a security manager already installed, this method first calls the security manager's checkPermission method with a RuntimePermission("setSecurityManager") permission to ensure it's ok to replace the existing security manager. This may result in throwing a SecurityException.

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211