How can a Runnable
be converted to a Supplier
?
public <T> T useSupplier(Supplier<T> supplier) {
// Does something with supplier and returns supplied value
...
return value;
}
public void useRunnable(Runnable runnable) {
// Somehow convert runnable to Supplier
...
useSupplier(supplier);
}
Here I would like to reuse the method useSupplier
for useRunnable
, for example because I do not want to duplicate the code. The behavior of useSupplier
does not matter for this question, let's say it wraps thrown exceptions, or uses the supplier in a synchronized block.
Edit: To clarify, the method useSupplier
does not interact with the supplied value, it just returns it. The functionality of useSupplier
is to retrieve the value from the supplier in some context, in my case it catches (specific) RuntimeException
s, creates a new exception with it as cause and throws it:
public <T> T useSupplier(Supplier<T> supplier) {
try {
return supplier.get();
}
catch (RuntimeException runtimeException) {
throw new MyException("Supplier threw exception", runtimeException);
}
}
The following solutions do not work (in Java 8):
useSupplier(runnable);
useSupplier(runnable::run);
useSupplier((Supplier<Void>) runnable::run);
One solution I could come up with is creating a new Supplier
which returns an arbitrary value:
useSupplier(() -> {
runnable.run();
return null;
});
Is there a smaller solution?
Edit: As pointed out by Holger in the comments, using runnable::run
will also create new lambda instances since it is stateful, see also this answer.
run
method returns void, so you can't supply any value. – MyogenicuseRunnable
I do not care about the returned value. As I wrote,useSupplier
uses for example the supplier in a synchronized block and this is what I want to have foruseRunnable
as well. – KhotanCallable
which returns a value, instead ofRunnable
. – CartwheeluseRunnable(...)
anduseSupplier(...)
? From the naming, it transports thatuseRunnable(...)
spawns a new threadt (at least for me). – MaybeRuntimeException
s and throwing new exceptions with them as cause. So I do not care about what value the supplier returned, I only return it as well. – Khotan() -> { runnable.run(); return null; }
does not create more objects thanrunnable::run
would. – Lonilonierrunnable::run
. No difference. – Lonilonier