What is the Thread.checkAccess() method in Java?

The checkAccess() method of the Thread class in Java is used to check whether the currently running thread has permission to modify the specified thread.

Syntax


void checkAccess(Thread thread)

Parameters

This method accepts only one parameter of the Thread type.

  • thread: This is the thread to be checked.

Return value

This method does not return any value.

Exception

The checkAccess() method throws the SecurityException exception if the currently running thread does not have permission to change resources.

Code

In the code snippet below, we have two threads, thread1 and thread2, named Thread-1 and Thread-2, respectively. As highlighted, we can use checkAccess() to check whether this thread has access to resources or not.

// Load Thread class
import java.lang.Thread;
// Main Class
public class MainThread extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName()+" execution finished");
}
// it will also throw exceptions
public static void main(String arg[]) throws SecurityException, InterruptedException {
// Creating the threads
MainThread thread1 = new MainThread();
MainThread thread2 = new MainThread();
// Start thread1
thread1.start();
thread1.setName("Thread-1");
// Start thread2
thread2.start();
thread1.setName("Thread-2");
// check for this thread
thread1.checkAccess();
System.out.println(thread1.getName() + " has access");
thread2.checkAccess();
System.out.println(thread2.getName() + " has access");
}
}

Free Resources