Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ScheduledExecutorService doesn't print stack trace?

Why we can't see the stacktrace in this example ?

public class NoStackTraceTester implements Runnable  {
    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    private ScheduledFuture<?> lifeCheckFuture;

    @Override
    public void run() {
        lifeCheckFuture = startLifecheck();
    }

    private ScheduledFuture<?> startLifecheck()
    {
        Runnable lifeCheck = new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("sending lifecheck ...");
                throw new RuntimeException("bang!");
            }
        };
        return scheduler.scheduleAtFixedRate(lifeCheck, 1000, 1000, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        new NoStackTraceTester().run();
    }
}

If you try to comment the exception you will the the repeative task of the lifecheck function. But if an exception is thrown, thread stop but with no detail :(

Do you have an idea why ?

like image 384
pepito Avatar asked Oct 06 '22 08:10

pepito


2 Answers

An ExecutorService places any captured Throwable in the Future object. If you inspect this you can see what exception was thrown. This is not always desirable so you may have to catch and handle or log any exception in the run() method.

Note: once an exception escapes, the task is not repeated again.

Runnable lifeCheck = new Runnable() {
    @Override
    public void run() {
        try {
            System.out.println("sending lifecheck ...");
            throw new RuntimeException("bang!");
        } catch(Throwable t) {
            // handle or log Throwable
        }
    }
};
like image 122
Peter Lawrey Avatar answered Oct 13 '22 03:10

Peter Lawrey


If you want an exception report, you must insert handling code yourself. The ExecutorService will not automatically send the exception trace to the standard output, and it is very good that it doesn't since this is rarely what we need in production code.

Basically, this is the approach:

public void run()
{
   try {
     System.out.println("sending lifecheck ...");
     throw new RuntimeException("bang!");
   } catch (Throwable t) { t.printStackTrace(); }
}
like image 45
Marko Topolnik Avatar answered Oct 13 '22 04:10

Marko Topolnik