How to Solve java.lang.IllegalStateException in Java main Thread?
Last Updated :
03 Mar, 2022
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");
}
}
Similar Reads
How to Solve IllegalArgumentException in Java?
An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. If an exception occurs, an Exception object is generated, contai
3 min read
How to Resolve a java.lang.AbstractMethodError in Java?
The java.lang.AbstractMethodError is a runtime error in Java that occurs when a class lacks the implementation of the abstract method declared in one of its interfaces or abstract parent classes. This error signifies a mismatch between the expected and actual class hierarchy. Syntax:public interface
2 min read
How to Handle a java.lang.ArithmeticException in Java?
In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca
2 min read
How to make ArrayList Thread-Safe in Java?
In Java, Thread is the smallest unit of execution within the program. It represents an independent path of execution that can run concurrently with other threads. When dealing with multi-threaded applications, where multiple threads are accessing and modifying data concurrently, it's crucial to ensu
3 min read
How to handle a java.lang.IndexOutOfBoundsException in Java?
In Java programming, IndexOutOfBoundsException is a runtime exception. It may occur when trying to access an index that is out of the bounds of an array. IndexOutOfBoundsException is defined as the RuntimeException. It can be used to find the out-of-bound run-time errors of an array. It is a part of
2 min read
How to Solve Deadlock using Threads in Java?
If two threads are waiting for each other forever such type of infinite waiting is called deadlock in java. Synchronized keyword is the only reason for deadlock situation hence while using synchronized keyword we have to take special care. There is no resolution technique for deadlock, but several p
6 min read
How to Get the Id of a Current Running Thread in Java?
The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. Java allows c
4 min read
Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe
In recent years object-oriented programming has formed the pillars/bases of Website and Application (Software) Development. Java and Python are popular Object-Oriented programming languages out of which the former one is offered and maintained by Oracle, while the latter one is open-source. Java alo
8 min read
How to Temporarily Stop a Thread in Java?
The suspend() method of thread class puts the thread from running to waiting state. This method is employed if you would like to prevent the thread execution and begin it again when a particular event occurs. This method allows a thread to temporarily cease execution. The suspended thread is often r
2 min read
How to Make a Java Thread Sleep for a Specific Duration?
Java is one of the famous programming languages for developing Real-time Applications. The Thread is a small unit of execution within a process, the Thread shares resources like files and memories with other threads in the same processor. For this, we have used Thread.sleep() method. This method tak
2 min read