228

ThreadPoolExecutorJavaのクラスを使用して、固定数のスレッドで多数の重いタスクを実行しようとしています。各タスクには、例外が原因で失敗する可能性のある多くの場所があります。

私はサブクラス化し、タスクの実行中に発生したキャッチされない例外を提供することになっているメソッドをThreadPoolExecutorオーバーライドしました。afterExecuteしかし、私はそれを機能させることができないようです。

例えば:

public class ThreadPoolErrors extends ThreadPoolExecutor {
    public ThreadPoolErrors() {
        super(  1, // core threads
                1, // max threads
                1, // timeout
                TimeUnit.MINUTES, // timeout units
                new LinkedBlockingQueue<Runnable>() // work queue
        );
    }

    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if(t != null) {
            System.out.println("Got an error: " + t);
        } else {
            System.out.println("Everything's fine--situation normal!");
        }
    }

    public static void main( String [] args) {
        ThreadPoolErrors threadPool = new ThreadPoolErrors();
        threadPool.submit( 
                new Runnable() {
                    public void run() {
                        throw new RuntimeException("Ouch! Got an error.");
                    }
                }
        );
        threadPool.shutdown();
    }
}

このプログラムからの出力は、「すべてが順調です-状況は正常です!」です。スレッドプールに送信された唯一のRunnableが例外をスローしたとしても。ここで何が起こっているのかについての手がかりはありますか?

ありがとう!

4

12 に答える 12

260

警告:このソリューションは呼び出し元のスレッドをブロックすることに注意してください。


タスクによってスローされた例外を処理する場合は、通常、を使用するCallableよりも使用する方が適切ですRunnable

Callable.call()チェックされた例外をスローすることが許可されており、これらは呼び出し元のスレッドに伝播されます。

Callable task = ...
Future future = executor.submit(task);
try {
   future.get();
} catch (ExecutionException ex) {
   ex.getCause().printStackTrace();
}

Callable.call()例外をスローする場合、これはでラップされ、ExecutionExceptionによってスローされFuture.get()ます。

これは、サブクラス化よりもはるかに好ましい可能性がありますThreadPoolExecutor。また、例外が回復可能な例外である場合は、タスクを再送信する機会も与えられます。

于 2010-02-11T22:15:12.170 に答える
164

ドキュメントから:

注:アクションが明示的にまたはsubmitなどのメソッドを介してタスク(FutureTaskなど)に囲まれている場合、これらのタスクオブジェクトは計算例外をキャッチして維持するため、突然の終了は発生せず、内部例外はこのメソッドに渡されません。 。

Runnableを送信すると、Futureにラップされます。

afterExecuteは次のようになります。

public final class ExtendedExecutor extends ThreadPoolExecutor {

    // ...

    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            System.out.println(t);
        }
    }
}
于 2010-02-11T22:21:05.923 に答える
19

この動作の説明は、afterExecuteのjavadocにあります

注:アクションが明示的にまたはsubmitなどのメソッドを介してタスク(FutureTaskなど)に囲まれている場合、これらのタスクオブジェクトは計算例外をキャッチして維持するため、突然の終了は発生せず、内部例外はこのメソッドに渡されません。 。

于 2010-02-11T22:21:42.043 に答える
16

エグゼキュータに送信された提供されたランナブルをラップすることで回避しました。

CompletableFuture.runAsync(() -> {
        try {
              runnable.run();
        } catch (Throwable e) {
              Log.info(Concurrency.class, "runAsync", e);
        }
}, executorService);
于 2014-12-14T11:14:20.210 に答える
6

私はjcabi-logのVerboseRunnableクラスを使用しています。これは、すべての例外を飲み込んでログに記録します。非常に便利です。例:

import com.jcabi.log.VerboseRunnable;
scheduler.scheduleWithFixedDelay(
  new VerboseRunnable(
    Runnable() {
      public void run() { 
        // the code, which may throw
      }
    },
    true // it means that all exceptions will be swallowed and logged
  ),
  1, 1, TimeUnit.MILLISECONDS
);
于 2012-05-10T15:49:35.843 に答える
4

別の解決策は、ManagedTaskManagedTaskListenerを使用することです。

インターフェースManagedTaskを実装するCallableまたはRunnableが必要です。

このメソッドgetManagedTaskListenerは、必要なインスタンスを返します。

public ManagedTaskListener getManagedTaskListener() {

そして、ManagedTaskListenerに次のtaskDoneメソッドを実装します。

@Override
public void taskDone(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception) {
    if (exception != null) {
        LOGGER.log(Level.SEVERE, exception.getMessage());
    }
}

管理対象タスクのライフサイクルとリスナーに関する詳細。

于 2015-11-11T08:17:55.410 に答える
2

これは動作します

  • SingleThreadExecutorから派生していますが、簡単に適応できます
  • Java 8 lamdasコードですが、修正は簡単です

単一のスレッドでエグゼキュータを作成し、多くのタスクを取得できます。現在の実行が終了して次の実行が開始されるのを待ちます

uncaugthエラーまたは例外の場合、uncaughtExceptionHandlerがそれをキャッチします

public final class SingleThreadExecutorWithExceptions {

    public static ExecutorService newSingleThreadExecutorWithExceptions(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler){

        ThreadFactoryファクトリ=(実行可能実行可能)-> {
            最終スレッドnewThread=new Thread(runnable、 "SingleThreadExecutorWithExceptions");
            newThread.setUncaughtExceptionHandler((final Thread caugthThread、final Throwable throwable)-> {
                uncaughtExceptionHandler.uncaughtException(caugthThread、throwable);
            });
            newThreadを返します。
        };
        新しいFinalizableDelegatedExecutorServiceを返します
                (新しいThreadPoolExecutor(1、1、
                        0L、TimeUnit.MILLISECONDS、
                        新しいLinkedBlockingQueue()、
                        工場){


                    protected void afterExecute(Runnable runnable、Throwable throwable){
                        super.afterExecute(runnable、throwable);
                        if(throwable == null && runnable instanceof Future){
                            試す {
                                Future future =(Future)runnable;
                                if(future.isDone()){
                                    future.get();
                                }
                            } catch(CancellationException ce){
                                スロー可能=ce;
                            } catch(ExecutionException ee){
                                throwable = ee.getCause();
                            } catch(InterruptedException ie){
                                Thread.currentThread()。interrupt(); //無視/リセット
                            }
                        }
                        if(throwable!= null){
                            uncaughtExceptionHandler.uncaughtException(Thread.currentThread()、throwable);
                        }
                    }
                });
    }



    プライベート静的クラスFinalizableDelegatedExecutorService
            DelegatedExecutorServiceを拡張します{
        FinalizableDelegatedExecutorService(ExecutorService executor){
            スーパー(エグゼキュータ);
        }
        保護されたvoidfinalize(){
            super.shutdown();
        }
    }

    / **
     *ExecutorServiceメソッドのみを公開するラッパークラス
     *ExecutorService実装の。
     * /
    プライベート静的クラスDelegatedExecutorServiceはAbstractExecutorServiceを拡張します{
        プライベートファイナルExecutorServicee;
        DelegatedExecutorService(ExecutorService executor){e = executor; }
        public void execute(Runnable command){e.execute(command); }
        public void shutdown(){e.shutdown(); }
        public List shutdownNow(){return e.shutdownNow(); }
        public boolean isShutdown(){return e.isShutdown(); }
        public boolean isTerminated(){return e.isTerminated(); }
        public boolean awaitTermination(long timeout、TimeUnit unit)
                InterruptedException{をスローします
            e.awaitTermination(timeout、unit);を返します。
        }
        public Future submit(実行可能なタスク){
            e.submit(task);を返します。
        }
        public Future submit(呼び出し可能なタスク){
            e.submit(task);を返します。
        }
        public Future submit(実行可能なタスク、T結果){
            e.submit(task、result);を返します。
        }
        パブリックリスト>invokeAll(コレクション>タスク)
                InterruptedException{をスローします
            e.invokeAll(tasks);を返します。
        }
        パブリックリスト>invokeAll(コレクション>タスク、
                                             長いタイムアウト、TimeUnitユニット)
                InterruptedException{をスローします
            e.invokeAll(tasks、timeout、unit);を返します。
        }
        public T invokeAny(コレクション>タスク)
                InterruptedException、ExecutionException{をスローします
            e.invokeAny(tasks);を返します。
        }
        public T invokeAny(Collection>タスク、
                               長いタイムアウト、TimeUnitユニット)
                InterruptedException、ExecutionException、TimeoutException{をスローします
            e.invokeAny(tasks、timeout、unit);を返します。
        }
    }



    private SingleThreadExecutorWithExceptions(){}
}
于 2017-05-16T16:41:36.393 に答える
1

タスクの実行を監視する場合は、1つまたは2つのスレッド(負荷によってはさらに多くのスレッド)をスピンし、それらを使用してExecutionCompletionServiceラッパーからタスクを取得できます。

于 2016-07-31T13:23:17.093 に答える
0

ExecutorService外部ソースからのものである場合(つまり、サブクラス化ThreadPoolExecutorしてオーバーライドafterExecute()することはできません)、動的プロキシを使用して目的の動作を実現できます。

public static ExecutorService errorAware(final ExecutorService executor) {
    return (ExecutorService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] {ExecutorService.class},
            (proxy, method, args) -> {
                if (method.getName().equals("submit")) {
                    final Object arg0 = args[0];
                    if (arg0 instanceof Runnable) {
                        args[0] = new Runnable() {
                            @Override
                            public void run() {
                                final Runnable task = (Runnable) arg0;
                                try {
                                    task.run();
                                    if (task instanceof Future<?>) {
                                        final Future<?> future = (Future<?>) task;

                                        if (future.isDone()) {
                                            try {
                                                future.get();
                                            } catch (final CancellationException ce) {
                                                // Your error-handling code here
                                                ce.printStackTrace();
                                            } catch (final ExecutionException ee) {
                                                // Your error-handling code here
                                                ee.getCause().printStackTrace();
                                            } catch (final InterruptedException ie) {
                                                Thread.currentThread().interrupt();
                                            }
                                        }
                                    }
                                } catch (final RuntimeException re) {
                                    // Your error-handling code here
                                    re.printStackTrace();
                                    throw re;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                }
                            }
                        };
                    } else if (arg0 instanceof Callable<?>) {
                        args[0] = new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                final Callable<?> task = (Callable<?>) arg0;
                                try {
                                    return task.call();
                                } catch (final Exception e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                }
                            }
                        };
                    }
                }
                return method.invoke(executor, args);
            });
}
于 2015-10-20T14:51:16.433 に答える
0

これは、以下のようにあなたを(何も)にAbstractExecutorService :: submit包んでいるためですrunnableRunnableFutureFutureTask

AbstractExecutorService.java

public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null); /////////HERE////////
    execute(ftask);
    return ftask;
}

次に、それをにexecute渡し、以下を呼び出します。WorkerWorker.run()

ThreadPoolExecutor.java

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
                !wt.isInterrupted())
                wt.interrupt();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    task.run();           /////////HERE////////
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

最後task.run();に、上記のコードで呼び出しはを呼び出します FutureTask.run()。これが例外ハンドラコードです。このため、予期された例外は発生しません。

class FutureTask<V> implements RunnableFuture<V>

public void run() {
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {   /////////HERE////////
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}
于 2016-05-12T08:32:03.777 に答える
0

これはmmmのソリューションに似ていますが、もう少しわかりやすくなっています。run()メソッドをラップする抽象クラスをタスクに拡張させます。

public abstract Task implements Runnable {

    public abstract void execute();

    public void run() {
      try {
        execute();
      } catch (Throwable t) {
        // handle it  
      }
    }
}


public MySampleTask extends Task {
    public void execute() {
        // heavy, error-prone code here
    }
}
于 2020-03-29T01:24:03.217 に答える
-5

ThreadPoolExecutorをサブクラス化する代わりに、新しいスレッドを作成してUncaughtExceptionHandlerを提供するThreadFactoryインスタンスを提供します。

于 2010-02-11T22:19:17.713 に答える