Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to call run method directly

Most of the time I want to run a block of code in a new thread where it does some time consuming stuff but in some circumstances I want to run it with the thread that called a method. Is it bad practice to directly call the run method?

If it is not a good idea is it best to put the code in another method which can be called by the new thread or duplicate the code?

This is some example code, it is just to illustrate what I want to achieve:

class Main {
    public Main() {
        new Thread(new WorkerThread(1, 2)).start(); // This is what I'd do if I wanted it to run in a new thread.
        new WorkerThread(1, 2).run(); // Is it bad practice to do this?
    }
}

class WorkerThread implements Runnable {
    private int int1, int2;

    public WorkerThread(int int1, int int2) {
        this.int1 = int1;
        this.int2 = int2;
    }

    public void run() {
        // Do something time consuming with the ints.
    }
}
like image 325
user2248702 Avatar asked Dec 02 '22 19:12

user2248702


2 Answers

I know there's already a lot of other answers, but your question is about "practice", and that word does not appear in any of them.

What is good practice is to write code that is easy for other people to understand and preferably, easy for them to understand without any in-line comments.

There is nothing wrong with calling foobar.run() as long as the meaning of "run" is obvious to somebody reading your program.

Your class is named WorkerThread even though it is not a thread. That might confuse people. And calling workerThread.run() might confuse them even more as to whether or not a thread actually is involved.

I would say, go ahead and call the run() method if that makes sense, but change the class so that readers know that you are not trying to start a thread and doing it the wrong way.

like image 113
Solomon Slow Avatar answered Dec 26 '22 05:12

Solomon Slow


Calling run executes the code synchronously; whereas run method would allow the code to execute asynchronously.

Calling run directly is often times beneficial in a testing scenarios where threading needs to be avoided.

like image 37
Suren Raju Avatar answered Dec 26 '22 06:12

Suren Raju