Java multithread exception handling

Article directory

  • 1. Handling of exceptions in threads
    • 1. The default behavior of a thread exception
    • 2. The setUncaoughtExceptionHandler() method handles exceptions
    • 3. SetDefaultUncaoughtExceptionHandler() method for exception handling
  • 2. An exception occurred in the thread group

1. Handling of exceptions in threads

1. The default behavior of thread exception

When an exception occurs in a single thread, we can handle it in the catch statement of the thread’s run() method. For processing, this will cause serious redundancy in the code. We can use setDefaultUncaoughtExceptionHandler() and method setUncaughtExceptionHandler() to focus on handling thread exceptions.

public class Main{<!-- -->
    public static void main(String[] args) {<!-- -->
        MyThread t = new MyThread();
        t. start();
    }
}
class MyThread extends Thread{<!-- -->
   @Override
    public void run(){<!-- -->
      String username=null;
       System.out.println(username.hashCode());
   }
}


As in the above program, after the program runs, the console outputs a null pointer exception. In java’s multithreading technology, we can capture exceptions in multithreading using the UncaughtExceptionHandler interface. So as to effectively handle exceptions. When a thread terminates due to an exception, the JVM virtual machine captures this situation and automatically calls the void uncaughtException(Thread t,Throwable e) method in the UncaughtExceptionHandler interface to handle the exception , to make exception handling more focused on multiple threads.

2. setUncaoughtExceptionHandler() method handles exception

public class Main{<!-- -->
    public static void main(String[] args) {<!-- -->
        MyThread t = new MyThread();
        t.setName("Thread t");
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {<!-- -->
            @Override
            public void uncaughtException(Thread t, Throwable e) {<!-- -->
                System.out.println("Thread:" + t.getName() + "An exception occurred");
            }
        });
        t. start();
        MyThread t2 = new MyThread();
        t2.setName("Thread t2");
        t2.start();
    }
}
class MyThread extends Thread{<!-- -->
   @Override
    public void run(){<!-- -->
      String username=null;
       System.out.println(username.hashCode());
   }
}

The function of the setUncaughtExceptionHandler method is to set the default exception handler for the specified thread object. In the Thread class, we can also use the setDefaultUncaoughtExceptionHandler method to set exception handlers for all threads

3. setDefaultUncaoughtExceptionHandler() method for exception handling

public class Main{<!-- -->
    public static void main(String[] args) {<!-- -->
        MyThread t = new MyThread();
        t.setName("Thread t");
        MyThread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {<!-- -->
            @Override
            public void uncaughtException(Thread t, Throwable e) {<!-- -->
                System.out.println("Thread:" + t.getName() + "An exception occurred");
                e.printStackTrace();
            }
        });
        t. start();
        MyThread t2 = new MyThread();
        t2.setName("Thread t2");
        t2.start();
    }
}
class MyThread extends Thread{<!-- -->
   @Override
    public void run(){<!-- -->
      String username=null;
       System.out.println(username.hashCode());
   }
}

Can be effective for all threads

2. An exception occurred in the thread group

The thread group (ThreadGroup) in Java is used to organize a group of threads together and provide some management and operation functions. However, Thread Groups are not commonly used in modern Java programming and have been marked as deprecated in Java 9. Nonetheless, we can describe possible anomalies and behaviors of thread groups. Here are some exceptions that may be related to thread groups:

  • IllegalThreadStateException (Illegal thread state exception): This exception may be thrown when trying to add a thread to a thread group that has been destroyed or a thread group has been terminated.

  • SecurityException (security exception): In some security-restricted environments, this exception may be thrown if there is insufficient permission to create or modify a thread group.

  • NullPointerException (null pointer exception): In some cases, trying to operate on an empty thread group object (such as adding threads, setting the thread group name, etc.) may cause this exception.

It should be noted that since thread groups are not commonly used in modern Java programming, exceptions related to thread groups may be rarely encountered in actual development. In order to better manage and organize threads, it is recommended to use higher-level concurrency tools, such as thread pools (ThreadPoolExecutor) and concurrent collections (ConcurrentHashMap, ConcurrentLinkedQueue, etc.).

public class Main{<!-- -->
    public static void main(String[] args) {<!-- -->
        ThreadGroup group=new ThreadGroup("Thread Group");
        MyThread[] myThreads=new MyThread[10];
        for (int i = 0; i < myThreads. length; i ++ ) {<!-- -->
            myThreads[i]=new MyThread(group,"Thread" + (i + 1),"1");
            myThreads[i].start();
        }
        MyThread newT=new MyThread(group,"error thread","aasdfsdf");
        newT. start();
    }
}
class MyThread extends Thread{<!-- -->
    private String num;
    public MyThread(ThreadGroup group,String name,String num){<!-- -->
        super(group,name);
        this.num=num;
    }
   @Override
    public void run(){<!-- -->
      int minINt=Integer. parseInt(num);
      while(true){<!-- -->
          System.out.println("in an infinite loop:" + Thread.currentThread().getName());
          try {<!-- -->
              Thread. sleep(1000);
          } catch (InterruptedException e) {<!-- -->
              throw new RuntimeException(e);
          }
      }
   }
}

After the program runs, one of the threads has an exception, while the other threads continue to print the results in an endless loop. Judging from the running results, by default, an exception in a thread in the thread group will not affect the running of other threads. See the code below:

public class Main{<!-- -->
    public static void main(String[] args) {<!-- -->
        MyThreadGroup group=new MyThreadGroup("Thread Group");
        MyThread[] myThreads=new MyThread[10];
        for (int i = 0; i < myThreads. length; i ++ ) {<!-- -->
            myThreads[i]=new MyThread(group,"Thread" + (i + 1),"1");
            myThreads[i].start();
        }
        MyThread newT=new MyThread(group,"error thread","aasdfsdf");
        newT. start();
    }
}
class MyThread extends Thread{<!-- -->
    private String num;
    public MyThread(ThreadGroup group,String name,String num){<!-- -->
        super(group,name);
        this.num=num;
    }
   @Override
    public void run(){<!-- -->
      int minINt=Integer. parseInt(num);
      while(this.isInterrupted()==false){<!-- -->
          System.out.println("in an infinite loop:" + Thread.currentThread().getName());
      }
   }
}
class MyThreadGroup extends ThreadGroup{<!-- -->
    public MyThreadGroup(String name){<!-- -->
        super(name);
    }
    @Override
    public void uncaughtException(Thread t,Throwable e){<!-- -->
        super.uncaughtException(t,e);
        this. interrupt();
    }
}

It can be seen that all threads are stopped. A custom thread group is used here, and uncaughtException is rewritten. When an exception occurs in a thread, the interrupt method is called to terminate all threads.