Don't use Runnable as a callback; it might cause confusion: people and code quality tools sometimes expect it to be used with threads only.
I did myself use Runnable as a callback — I thought it seemed fairly well suited for use as a generic callback. A month later someone found my code snipped:
doneCallback.run();
and he noticed that the doneCallback
was a Runnable
, and that invoking .run()
directly resulted in a warning in our code quality analysis program (Sonar). So, to fix the warning?, or because he thought the intention was to create a thread?, he forked a new thread, and called run()
via that thread instead.
However, forking a thread there, broke stuff.
To avoid confusion, now I'm instead creating a generic callback interface that's not related to threads in any way. I'm just adding a class Callback
with a method call
. I think I'd better not use java.util.concurrent.Callback
because that one is related to threads too.
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
So, as KajMagnus experienced, people might expect the Runnable to be associated with a thread, and find this usage confusing. I agree with KajMagnus that defining an Interface specific to this usage is clearer. – Aisne