Fork/Join中的异常处理

(1)继承关系

              ThreadPoolExecutor:

             

              ForkJoinPool

                 

              可以看出他们的父类都是AbstractExecutorService,所以也ForkJoinPool可以通过execute和submit来执行线程


(2)execute调用

                1.背景

                 一般线程池中线程,如果通过execute来执行,那么可以通过设置UncaughtExceptionHandler的方式来处理UncheckedException

                但是在ForkJoinPool中无法设置ThreadFactory,所以不能与线程池一样处理异常


                2.处理思路

                    1)通过task.isDone()判断是否执行结束

                    2)如果结束了,同task.isCompletedAbnormally()判断是否抛出了异常


                3.实例

import java.util.concurrent.RecursiveAction;

public class ExceptionTask extends RecursiveAction{
	
	private static final long serialVersionUID = -1748204943733764733L;
	
	private static final int THRESHOLD = 10;// 阈值
	
	private int begin;
	
	private int end;
	
	public ExceptionTask(int begin, int end) {
		super();
		this.begin = begin;
		this.end = end;
	}

	@Override
	protected void compute() {
		if (begin-end<THRESHOLD) {
			if (begin<3 && 3<end) {//当begin<3<end的时候就抛出异常
				throw new RuntimeException("test exception");
			}
		}else {
			int mid = (begin+end)>>>1;
			
			invokeAll(new ExceptionTask(begin, mid), new ExceptionTask(mid+1, end));
		}
	}

}
                 测试
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ExceptionTaskTest {

	@Test
	public void test() throws InterruptedException {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		
		int[] a = new int[10];
		Random random = new Random();
		for (int i = 0; i < a.length; i++) {
			a[i] = random.nextInt(99);
		}
		ExceptionTask task = new ExceptionTask(0, a.length-1);
		forkJoinPool.execute(task);
//		forkJoinPool.awaitTermination(1, TimeUnit.SECONDS);
		while(!task.isDone()){
			TimeUnit.MILLISECONDS.sleep(50);
			System.out.println("task is executing...");
		}
		if (task.isCompletedAbnormally()) {
			System.out.println("an exception has been throwed");
			System.out.println(task.getException());
		}else {
			System.out.println("no exception");
		}
		
		forkJoinPool.shutdown();
	}
}
             结果为:

task is executing...
an exception has been throwed
java.lang.RuntimeException: java.lang.RuntimeException: test exception


(3)submit调用

                1.背景

                    线程池通过submit调用,如果没有对Future调用get,会吃掉异常。

                    使用ForkJoinPool仍然会有这种问题


                2.解决思路

                    仍然调用返回值的get方法

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ExceptionTaskTest {

	@Test
	public void test() throws InterruptedException {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		
		int[] a = new int[10];
		Random random = new Random();
		for (int i = 0; i < a.length; i++) {
			a[i] = random.nextInt(99);
		}
		ExceptionTask task = new ExceptionTask(0, a.length-1);

		ForkJoinTask<Void> result = forkJoinPool.submit(task);
		try {
			result.get();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		forkJoinPool.awaitTermination(3, TimeUnit.SECONDS);
		if (task.isCompletedAbnormally()) {
			System.out.println("an exception has been throwed");
			System.out.println(task.getException());
		}else {
			System.out.println("no exception");
		}
		
		forkJoinPool.shutdown();
	}
}
              结果为:

java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.lang.RuntimeException: test exception
	at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:942)
	at com.test.ExceptionTaskTest.test(ExceptionTaskTest.java:38)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.RuntimeException: test exception
	at com.test.ExceptionTask.compute(ExceptionTask.java:25)
	at java.util.concurrent.RecursiveAction.exec(RecursiveAction.java:177)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:334)
	at java.util.concurrent.ForkJoinWorkerThread.execTask(ForkJoinWorkerThread.java:604)
	at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:784)
	at java.util.concurrent.ForkJoinPool.work(ForkJoinPool.java:646)
	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:398)
an exception has been throwed
java.lang.RuntimeException: java.lang.RuntimeException: test exception


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值