3

In the documentation of the interrupt() method we have:

Throws:
    SecurityException - if the current thread cannot modify this thread

The source code of the method is this:

public void interrupt() {
     if (this != Thread.currentThread())
         checkAccess();   //checking access
     //The rest is ommited
 }

The checkAccess method, in turn is implemented as follows:

public final void checkAccess() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkAccess(this);
    }
}

By default, as far as I got any thread is permitted to modify anyone else thread.

But is there a way to specify modifyThread permission in the java.policy file to allow a thread modify only itself?

In the java.policy I could find the only grant{ ... } section. Is there a way to deny such threads communications?

dimo414
  • 47,227
  • 18
  • 148
  • 244
St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

1

In order for you to use policy files to control who can call Thread.interrupt() there would need to be a policy in place which regulates this access. As you've seen there isn't a SecurityManager.checkPermission() call in Thread.interrupt(), so this is clearly not possible. This is by design, because policies are meant to limit the access of code sources, not threads (which can be executing code from multiple source locations). If a code source is not granted access to a certain policy, it can never run code protected by that policy.

Instead, Thread access is regulated by the SecurityManager.checkAccess(Thread) method. From Thread.checkAccess():

Determines if the currently running thread has permission to modify this thread.

If there is a security manager, its checkAccess method is called with this thread as its argument.

And SecurityManager.checkAccess(Thread) describes exactly how you can restrict access:

Throws a SecurityException if the calling thread is not allowed to modify the thread argument.

This method is invoked for the current security manager by the stop, suspend, resume, setPriority, setName, and setDaemon methods of class Thread. [sic. this should include interrupt as well]

.... If the thread argument is not a system thread, this method just returns silently.

Applications that want a stricter policy should override this method....

So there you go. Define a custom SecurityManager that raises an exception in checkAccess(Thread) to restrict who can interrupt or otherwise modify threads..


To your second question about granting vs. denying permissions, the Policy File Syntax page details that there is only the grant statement, there is no deny mechanism.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244