How to solve the Java method invocation rejected error exception (MethodInvocationRejectedErrorExceotion)
Introduction:
In Java programming, when we use multi-threading or thread pool to execute When calling a method, you may sometimes encounter a method invocation rejected error exception (MethodInvocationRejectedErrorExceotion). This exception prevents the thread from properly executing the method and may cause the program to terminate. This article describes how to resolve this exception and provides corresponding code examples.
Exception reason:
Method call rejected error exception is usually caused by resource limitations of the thread pool. When the number of threads in the thread pool reaches the maximum limit and a new method call request comes in, the thread pool will refuse to call the method and throw an exception.
Solution:
The following are several solutions, you can choose the solution that suits you according to the specific situation.
ExecutorService executor = Executors.newFixedThreadPool(10); //创建一个固定大小为10的线程池 ((ThreadPoolExecutor)executor).setMaximumPoolSize(20); //增加最大线程数量为20
ThreadPoolExecutor executor = new ThreadPoolExecutor( 10, //核心线程数量 20, //最大线程数量 60, //线程保持活跃时间 TimeUnit.SECONDS, //活跃时间的单位 new LinkedBlockingQueue<Runnable>(), //任务队列 new ThreadPoolExecutor.CallerRunsPolicy()); //非阻塞策略,将未处理的任务返回给调用方
ThreadPoolExecutor executor = new ThreadPoolExecutor( 10, //核心线程数量 20, //最大线程数量 60, //线程保持活跃时间 TimeUnit.SECONDS, //活跃时间的单位 new ArrayBlockingQueue<Runnable>(100)); //有界任务队列,最大容量为100
ThreadPoolExecutor executor = new ThreadPoolExecutor( 10, //核心线程数量 20, //最大线程数量 60, //线程保持活跃时间 TimeUnit.SECONDS, //活跃时间的单位 new LinkedBlockingQueue<Runnable>(), //任务队列 new RejectedExecutionHandler() { //自定义拒绝策略 @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { //执行自定义的处理逻辑,例如日志记录或抛出自定义异常 } });
Summary:
When encountering a Java method call rejected error exception (MethodInvocationRejectedErrorExceotion), we can increase the thread pool capacity and use non-blocking threads Pool, use a bounded queue, or set a deny policy to resolve this exception. Choosing the appropriate solution based on the specific situation can ensure that the thread pool can handle all method call requests normally and improve the stability and reliability of the program.
Reference:
The above is the detailed content of How to solve Java method invocation rejected error exception (MethodInvocationRejectedErrorExceotion). For more information, please follow other related articles on the PHP Chinese website!