Bad practice using Runnable as a callback / routine?

Is using Runnable as a callback considered improper?

Given that Runnable intended for use with threads (see its JavaDoc), I wonder if everything is in order - or should I make my own interface for this purpose.

What I'm talking about is something like:

 public class KeyBinding { public KeyBinding(KeyStroke stroke, Runnable handler) { //... } } 
+9
java runnable callback
Mar 28 '14 at 21:35
source share
2 answers

In fact, Runnables can be used for any purpose.

"The general contract of a method is that it can take any action" ( Runnable javadoc )

As a rule, this should not be bad practice, definitely a better practice than creating an unnecessary unnecessary interface in your own code.

+5
Mar 28 '14 at 21:57
source share

Do not use Runnable as a callback; this can be confusing: people and code quality tools sometimes expect them to be used only with threads.

I myself used Runnable as a callback - I thought it looked quite suitable for use as a general callback. A month later, someone found that my code was disabled:

 doneCallback.run(); 

and he noticed that doneCallback was Runnable , and that calling .run() directly caused a warning in our code quality analysis program (Sonar). So, to fix the warning ?, or because he thought the goal was to create a thread ?, he forked a new thread and called run() through that thread.

However, unrolling the flow, he broke the material.

To avoid confusion, I now instead create a common callback interface that has nothing to do with threads. I just add the Callback class using the call method. I think I better not use java.util.concurrent.Callback , because this is also thread related.

+13
May 12 '15 at 6:53
source share



All Articles