Thursday, February 8, 2018

Yoda Pattern

In the previous part, I talked about the Medusa Pattern, where I limited the number of threads. Now I want to go even further: I want to remove all threads.
In fact, there is a particular case where threads are more of a nuisance. I am thinking about the small creature that likes the green color: the unit tests. As Yoda would say: “too much faith in threads you have”. When faced with multithreading in a unit test, you often have to revert to inserting sleep() commands, or performing some more complex tricks using wait() and notify() or equivalent.
But in reality, what you would really like to do is to get rid of the threads just for the testing. If you are using an Executor, it is not complicated to replace it with another one that executes the task in the current thread:
Executor forTest = new Executor() {
   public void execute(Runnable command) {
       command.run();
   }
};
Since we are using Java 8 (at least) and Executor is a functional interface, we can revert to use a lambda:
Executor forTest = command -> command.run;
And even better to use method reference:
Executor forTest = Runnable::run;

No comments:

Post a Comment