Open In App

How to Solve java.lang.IllegalStateException in Java main Thread?

Improve
Improve
Like Article
Like
Save
Share
Report

An unexpected, unwanted event that disturbed the normal flow of a program is called Exception.

Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException.  If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.

There are mainly two types of exception  in java as follows:

1. Checked Exception:

The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exception then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get compile-time error.

Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.

2. Unchecked Exception:

The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception.

Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException etc.

Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.

IllegalStateException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise explicitly by programmer or by the API developer to indicate that a method has been invoked at the wrong time. Generally, this method is used to indicate a method is called at an illegal or inappropriate time.

Example: After starting a thread we are not allowed to restart the same thread once again otherwise we will get Runtime Exception saying IllegalStateException.

Example 1: We call start() method when it’s already executing the run() method.

Java




// Java program to show the occurrence of
// IllegalStateException.
 
// Import required packages
 
import java.io.*;
import java.util.*;
 
// Creating a thread in our myThread class by extending the
// Thread class
// class 1
// Helper class
 
class myThread extends Thread {
   
    // Method in helper class
    // declaring run method
    public void run()
    {
 
        for (int i = 0; i < 5; i++) {
           
            // Display message
            System.out.println("GeeksForGeeks");
        }
    }
}
 
// class 2
// Main class
class Thread1 {
   
    // Main driver method
    public static void main(String[] args)
    {
        // creating a thread object  in the main() method
        // of our helper class above
        myThread t = new myThread();
       
        // Starting the above created thread
        // using the start() method
        t.start();
       
        // Display Message
        System.out.println("Main Thread");
       
        // starting the thread again when it is already
        // running and hence it cause an exception
        t.start();
    }
}



Example 2: We call start() method on a thread when it has finished executing run() method. 

Java




// Java program to show the occurrence of
// IllegalStateException.
 
// Import required packages
import java.io.*;
import java.util.*;
 
// Creating a thread in our myThread class by extending the
// Thread class
// class 1
// Helper class
class myThread extends Thread {
   
    // Method in helper class
    // declaring run method
    public void run()
    {
 
        for (int i = 0; i < 5; i++) {
           
            // Display message
            System.out.println("GeeksForGeeks");
        }
    }
}
 
// class 2
// Main class
class Thread1 {
   
    // Main driver method
    public static void main(String[] args)
    {
        // creating a thread object  in the main() method
        // of our helper class above
        myThread t = new myThread();
       
        // Starting the above created thread
        // using the start() method
        t.start();
       
        try {
            System.out.println("Main Thread is going to sleep");
           
            // making main thread sleep for 2000ms
            t.sleep(2000);
            System.out.println("Main Thread awaken");
        }
        catch (Exception e) {
            System.out.println(e);
        }
 
        // Display Message
        System.out.println("Main Thread");
       
        // calling start( ) method on a dead thread
        // which causes exception
        t.start();
    }
}



 How to solve this error?

In order to avoid java.lang.IllegalStateException in Java main Thread we must ensure that any method in our code cannot be called at an illegal or an inappropriate time.

In the above example if we call start() method only once on thread t then we will not get any java.lang.IllegalStateException because we are not calling the start() method after the starting of thread (i.e we are not calling the start() method at an illegal or an inappropriate time.) 

Java




// Java program to demonstrate that the error
// does not occur in this program
 
// Import required packages
import java.io.*;
import java.util.*;
 
// Creating a thread in our myThread class by extending the
// Thread class
// class 1
// Helper class
class myThread extends Thread {
   
    // Method in helper class
    // declaring run method
    public void run()
    {
 
        for (int i = 0; i < 5; i++) {
           
            // Display message
            System.out.println("GeeksForGeeks");
        }
    }
}
 
// class 2
// Main class
class Thread1 {
   
    // Main driver method
    public static void main(String[] args)
    {
        // creating a thread object  in the main() method
        // of our helper class above
        myThread t = new myThread();
       
        // Starting the above created thread
        // using the start() method
        t.start();
       
        try {
            System.out.println("Main Thread is going to sleep");
           
            // making main thread sleep for 2000ms
            t.sleep(2000);
           
            System.out.println("Main Thread awaken");
        }
        catch (Exception e) {
            System.out.println(e);
        }
 
        // Display Message
        System.out.println("Main Thread");
    }
}



 



Last Updated : 03 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads