Package com.jcabi.log

Class VerboseThreads

  • All Implemented Interfaces:
    ThreadFactory

    public final class VerboseThreads
    extends Object
    implements ThreadFactory
    Convenient 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.

    Since:
    0.1.2
    See Also:
    VerboseRunnable
    • Constructor Detail

      • VerboseThreads

        public VerboseThreads()
        Default constructor ("verbose" as a prefix, threads are daemons, default thread priority is 1).
      • VerboseThreads

        public VerboseThreads​(String pfx)
        Detailed constructor, with a prefix of thread names (threads are daemons, default thread priority is 1).
        Parameters:
        pfx - Prefix for thread names
      • VerboseThreads

        public VerboseThreads​(Object type)
        Detailed constructor, with a prefix of thread names (threads are daemons, default thread priority is 1).
        Parameters:
        type - Prefix will be build from this type name
      • VerboseThreads

        public VerboseThreads​(Class<?> type)
        Detailed constructor, with a prefix of thread names (threads are daemons, default thread priority is 1).
        Parameters:
        type - Prefix will be build from this type name
      • VerboseThreads

        public VerboseThreads​(String pfx,
                              boolean dmn,
                              int prt)
        Detailed constructor.
        Parameters:
        pfx - Prefix for thread names
        dmn - Threads should be daemons?
        prt - Default priority for all threads