Ian Hu
Ian Hu

Reputation: 305

how can i forbid a jar create new thread in java

I have create a simple plugin system that allows others upload their plugin's jar, and the plugin system will load it and execute some code in it.

the plugin system will get a subclass of Function<Input, Output> to execute the loaded plugin logic, but I do not want that Function to create new Thread or do some danger action like System.exit. how can I forbid this action?

I have found the AccessController or SecurityManager in Java, how to use it to implement my intent.

Upvotes: 0

Views: 124

Answers (2)

GhostCat
GhostCat

Reputation: 140427

For System.exit() - see the other answer.

For preventing the starting of threads: possible, but requires to extend the SecurityManager class - see here.

AccessController is more about how a client would write code that is potentially checked. It is not something that you, as the "owner" of the JVM can make usage of (see here). So it doesn't help with your problem.

Upvotes: 1

Optional
Optional

Reputation: 4507

Like you said, you can add a security Manager. Something like below: You can put your code in try catch block and catch your custom security exception thrown. This code below runs in loop and keeps on calling System.exit(1);

import java.security.Permission;

public class TestPreventSystemExit {

    public static void main(String[] args) {
        forbidSystemExitCall();
        while (true) {
            try {
                System.exit(1);
            } catch (Exception ex) {

            }
        }
    }

    private static class PreventExitException extends SecurityException {
    }

    private static void forbidSystemExitCall() {
        final SecurityManager securityManager = new SecurityManager() {
            public void checkPermission(Permission permission) {
                if (permission.getName().indexOf("exitVM") >= 0) {
                    System.out.println("Why you did this to me? :)");
                    throw new PreventExitException();
                }
            }
        };
        System.setSecurityManager(securityManager);
    }

}

Upvotes: 4

Related Questions