Thread Factory that Logs Exceptions
VerboseThreads
is an implementation of ThreadFactory
that instantiates threads that log all runtime exceptions through SLF4J.
VerboseThreads
factory should be used together with executor services from java.util.concurrent
package. Without this "verbose" thread factory your runnable tasks will not report anything to console once they die because of a runtime exception, for example:
public class Main { public static void main(String[] args) { Executors.newScheduledThreadPool(2).scheduleAtFixedRate( new Runnable() { @Override public void run() { // some sensitive operation that may throw // a runtime exception } }, 1L, 1L, TimeUnit.SECONDS ); } }
The exception in this example will never be caught by nobody. It will just terminate current execution of the Runnable
task. Moreover, it won't reach any Thread.UncaughtExceptionHandler
, because this is how ScheduledExecutorService
is behaving by default. This is how we solve the problem with VerboseThreads
:
public class Main { public static void main(String[] args) { ThreadFactory factory = new VerboseThreads(); Executors.newScheduledThreadPool(2, factory).scheduleAtFixedRate( new Runnable() { @Override public void run() { // the same sensitive operation that may throw // a runtime exception } }, 1L, 1L, TimeUnit.SECONDS ); } }
Now, every runtime exception that is not caught inside your Runnable
will be reported to log (using Logger
).
The only dependency you need is (you can also download jcabi-log-0.24.3.jar
and add it to the classpath):
<dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-log</artifactId> <version>0.24.3</version> </dependency>