public final class VerboseThreads extends Object implements ThreadFactory
ThreadFactory
, that logs all uncaught exceptions.
The factory should be used together
with executor services from java.util.concurrent
package. Without
these "verbose" threads your runnable tasks will not report anything to
console once they die because of a runtime exception, for example:
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. This is how we solve
the problem with VerboseThreads
:
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
).
This class is thread-safe.
VerboseRunnable
Constructor and Description |
---|
VerboseThreads()
Default constructor (
"verbose" as a prefix, threads are daemons,
default thread priority is 1 ). |
VerboseThreads(Class<?> type)
Detailed constructor, with a prefix of thread names (threads are daemons,
default thread priority is
1 ). |
VerboseThreads(Object type)
Detailed constructor, with a prefix of thread names (threads are daemons,
default thread priority is
1 ). |
VerboseThreads(String pfx)
Detailed constructor, with a prefix of thread names (threads are daemons,
default thread priority is
1 ). |
VerboseThreads(String pfx,
boolean dmn,
int prt)
Detailed constructor.
|
public VerboseThreads()
"verbose"
as a prefix, threads are daemons,
default thread priority is 1
).public VerboseThreads(String pfx)
1
).pfx
- Prefix for thread namespublic VerboseThreads(Object type)
1
).type
- Prefix will be build from this type namepublic VerboseThreads(Class<?> type)
1
).type
- Prefix will be build from this type namepublic VerboseThreads(String pfx, boolean dmn, int prt)
pfx
- Prefix for thread namesdmn
- Threads should be daemons?prt
- Default priority for all threadspublic Thread newThread(Runnable runnable)
newThread
in interface ThreadFactory
Copyright © 2012 jcabi.com. All Rights Reserved.