Package com.guinetik.corefun
Interface SafeRunnable
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
A functional interface for operations that may throw checked exceptions.
SafeRunnable allows writing lambda expressions for operations that throw
checked exceptions, which can then be converted to standard Runnable
instances with automatic exception wrapping. This eliminates the boilerplate
of try-catch blocks in lambda expressions.
Problem Solved
Java's Runnable interface declares void run() without any
checked exceptions. This makes it impossible to use lambdas that throw checked
exceptions directly with executors or other APIs expecting Runnable.
Example Usage
// Define an operation that throws checked exceptions
SafeRunnable task = () -> {
Files.delete(path); // throws IOException
};
// Convert to standard Runnable for use with executors
executor.execute(task.toRunnable());
// Or execute immediately with automatic wrapping
task.execute(); // throws SafeException on failure
// Create from existing Runnable
SafeRunnable fromRunnable = SafeRunnable.from(() -> doSomething());
- Since:
- 0.1.0
- Author:
- Guinetik <guinetik@gmail.com>
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptiondefault voidexecute()Executes this SafeRunnable, wrapping any exception.static SafeRunnableCreates a SafeRunnable from a standard Runnable.voidrun()Executes the operation, potentially throwing a checked exception.default RunnableConverts this SafeRunnable to a standard Runnable.
-
Method Details
-
run
Executes the operation, potentially throwing a checked exception.- Throws:
Exception- if the operation fails
-
toRunnable
Converts this SafeRunnable to a standard Runnable. Any checked exceptions are wrapped inSafeException.- Returns:
- a Runnable that wraps checked exceptions
-
from
Creates a SafeRunnable from a standard Runnable.- Parameters:
runnable- the Runnable to wrap- Returns:
- a SafeRunnable that delegates to the Runnable
-
execute
default void execute()Executes this SafeRunnable, wrapping any exception. Convenience method for immediate execution.- Throws:
SafeException- if execution fails
-