0

Let assume, I have some resource and time-consuming code, which I want to arrange as a separate method. In order to optimize the performance, this code should be executed in the separate thread.

Now the question, where to define this thread:

  1. Inside (built-in) of this «heavy» method;
  2. Or to wrap the execution of this «heavy» class's code by the thread.

In other words, from the design and the best practice point of view, should I built-in the separate thread execution or it is better to write this code without threads and if there is a need to execute this code in the separate thread, the developer will wrap it by the separate thread?

Update:
The main reason I ask this question is that I want to provide a turnkey solution, which can used as a plug-and-play black box, and not to worry if the end-user will forget to execute this code in the separate thread.

1
  • This might depend on how the heavy method will be called. How will your main application thread know the heavy method has completed? Is the heavy method returning data? Depending on your needs you may need to provide callers of your heavy method ways to know when the method execution is complete, or ways to access data returned from the thread. This would likely remove your ability to hide the threading implementation completely within the method. – Rich Rousseau Jul 14 '15 at 13:05
4

Separate your concerns. Complicated business logic should never be intermingled with scheduling logic that is also complex. Therefore, implement whatever smart solution you want, but wrap it into a well-named method and then schedule that.

2
  • Thanks for the answer. The main reason I ask this question is that I want to provide a turnkey solution, which can used as a plug-and-play black box, and not to worry if the end-user will forget to execute this code in the separate thread. – Mike B. Jul 14 '15 at 13:16
  • 1
    +1 for Design-principle Separation_of_concerns – k3b Jul 14 '15 at 14:21
0

If your implementation of the heavy logic is an ordenary, thread-free method it is much easier to write testcode (unit/integration-Tests) for it and to debug it. Writing junit-tests for threads is a nightmare.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.