Interface CatchingRunnable2

All Superinterfaces:
Runnable
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@Beta @FunctionalInterface public interface CatchingRunnable2 extends Runnable
Copied and modified from kiwi's CatchingRunnable. The changes include:
  • The ability to provide a name, which is used when reporting unexpected exceptions
  • Factory methods to easily create an instance with or without a name and exception handler
These features may or may not ever be added to kiwi.

Original documentation from kiwi:

Extension of Runnable that never lets exceptions escape. Useful for things like scheduled executions using ScheduledExecutorService where an intermittent error should not cause the executor to suppress future executions (which is the default behavior).

  • Method Details

    • of

      static CatchingRunnable2 of(Runnable runnable)
      Create a new instance wrapping the given Runnable.
    • of

      static CatchingRunnable2 of(Runnable runnable, Consumer<Exception> exceptionHandler)
      Create a new instance wrapping the given Runnable. Uses the given Consumer to handle unexpected exceptions thrown by the Runnable.
    • of

      static CatchingRunnable2 of(String name, Runnable runnable)
      Create a new instance with the given name that wraps the given Runnable.
    • of

      static CatchingRunnable2 of(String name, Runnable runnable, Consumer<Exception> exceptionHandler)
      Create a new named-instance wrapping the given Runnable. Uses the given Consumer to handle unexpected exceptions thrown by the Runnable.
    • name

      default Optional<String> name()
      Returns a name, if available, which can be used to differentiate instances. The name is used when logging exceptions thrown by the Runnable or by the exception handler defined in handleExceptionSafely(java.lang.Exception).

      For example, if an application uses multiple scheduled tasks to perform background actions and wraps those tasks with CatchingRunnable2, then providing a name can provide context when logging exceptions.

      Returns:
      an Optional with the name of this instance
    • run

      default void run()
      Wraps runSafely() in a try/catch. Logs exceptions and will call handleExceptionSafely(Exception) to permit handling of any thrown exceptions.
      Specified by:
      run in interface Runnable
    • handleExceptionSafely

      default void handleExceptionSafely(Exception exception)
      Handle an exception thrown by runSafely().
      Parameters:
      exception - the Exception to handle
    • runSafely

      void runSafely()
      The logic that could throw a RuntimeException.