Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good thread design: "Method in Thread" or "Thread in Method"

This is just a general question on actual thread design. I'm using Java on android specifically but general design would be the better focus of this question.

Its simple enough, which is better method in thread or thread in method.

Example,

Lets say we have 3 methods/functions/whatever.

public void readMail()
{
    //Logic...
}
public void postQuestion()
{
    //Logic...
}
public void answerQuestion()
{
    //Logic...
}

Is it better to have


A: Thread within Method

public void readMail()
{
    new Thread(new Runnable()
    {
        public void run()
        {
            //Logic
        }
    }).start();
}

And then call your method as you normally would in any OO situation. Say

Email.readMail();

B: Method within Thread

//note this could be inside a method or a class that extends runnable
new Thread(new Runnable()
{
    public void run()
    {
        readMail();
        postQuestion();
        answerQuestion();
    }
}).start();
like image 658
OVERTONE Avatar asked Oct 29 '25 18:10

OVERTONE


1 Answers

Method within Thread

  • [+] If your methods do not need to ensure the property of concurrent execution, or they have deterministic runtime behavior (time and performance), this approach can be a high-level management for concurrency of the application; i.e. concurrency remains at the level of objects rather than methods.
  • [-] Since the concurrency remains at the level of threads/objects, the application may lose the notion of responsiveness. A user may be "posting a question" while another is "fetch an answer"; and both can be dealt with concurrently.

Thread with Method

  • [+] More fine-grained concurrency control: each method becomes a unit of execution at the OS level. That's why as @LouisWasserman mentioned, maybe, taking advantage of Executor framework would make more sense.
  • [-] Generally threads are resourceful and expensive; so this means that you will have performance issues when used in high-frequency/load application with numerous calls to one method. Specially, if there are inter-method data/logic dependencies. In this regard, synchronization also becomes a concerns and that's why using Actor models can help more.

I'd suggest reading more about Actor models and their available implementations.

like image 115
nobeh Avatar answered Nov 01 '25 08:11

nobeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!