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

This is just a general question about the actual design of threads. I'm using Java on Android on purpose, but general design would be the best direction for this question.

Its simple enough which is better in a stream or a stream in a method.

Example

Let's 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: flow within a method

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

      

And then call your method as usual in any OO situation. Tell

Email.readMail();

      


B: Method in a stream

//note this could be inside a method or a class that extends runnable
new Thread(new Runnable()
{
    public void run()
    {
        readMail();
        postQuestion();
        answerQuestion();
    }
}).start();

      

+3


source to share


5 answers


Method in a stream

  • [+] If your methods do not need to guarantee the property of parallel execution or they have deterministic behavior at runtime (time and performance), this approach can be high-level control for a concurrency application; that is, concurrency remains at the object level, not methods.
  • [-] Since concurrency remains at the thread / object level, the application may lose the concept of responsiveness. A user can "submit a question" and another can "receive an answer"; and both can be viewed at the same time.

Thread with Method



  • [+] A finer-grained concurrency control: each method becomes a unit of execution at the OS level. This is why, as @LouisWasserman said, maybe using a framework Executor

    makes sense.
  • [-] In general, flows are resourceful and expensive; so this means you will have performance issues when used in a high frequency / load application with multiple calls to the same method. Especially if there are interconnected data / logical dependencies. Synchronization is also becoming a problem in this respect, and why using Actor models can help more.

I would suggest reading more about Actor Models and their available implementations.

+4


source


The second option is more rewritable to use Executor

and the like, so I would prefer this version.



+4


source


I prefer:


C: one object with one thread

public class Test {
  public static class MailReader implements Runnable {
    public void readMail() {
      //Logic...
    }
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        readMail();
      }
    }
  }

  public static class QuestionPoster implements Runnable {
    public void postQuestion() {
      //Logic...
    }
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        postQuestion();
      }
    }
  }

  public static class QuestionAnswerer implements Runnable {
    public void answerQuestion() {
      //Logic...
    }
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        answerQuestion();
      }
    }
  }
  public static void main(String[] args) throws FileNotFoundException {
    new Thread(new QuestionAnswerer()).start();
    new Thread(new QuestionPoster()).start();
    new Thread(new MailReader()).start();
  }
}

      

This allows you to use the full range of possibilities without any additional effort. If you want to receive more emails than the questions asked, do more MailReader

s.

If you see

for ( int i = 0; i < 10; i++ ) {
  new Thread(new MailReader()).start();
}

      

you know exactly what is intended and you know it will work.

+1


source


Design first (A), each method is a SEPARATE THREAD, while in the second design (B), you have ONLY ONE THREAD.
It depends a lot on your application logic and the operation that each method performs:
If you need to run methods in parallel, then A is the correct answer, but if you need to execute all methods sequentially in a thread, then B.

0


source


If you are writing a utility for use by other programmers, note that the client programmer might not care about threads at all and might just write a single threaded program. Unless there is a compelling reason to do so, you shouldn't be making them drag and drop threading issues into a program that would otherwise work fine single-threaded. Does this mean that your library cannot use streams internally? Not! But to the caller, your methods should appear single-threaded (except that they return faster than if they were implemented without threads).

How can you do this? When someone calls one of your methods, block the calling thread and submit the task to a pool of worker threads that can execute it in parallel. After the worker threads have completed the task, unblock the calling thread and allow it to return a value to the caller.

This way you can get the performance benefits of parallelism without forcing callers to deal with threading issues.

Now, on the other hand, even if you decide that your library doesn't need to use threads internally, you still need to make it thread safe, because client programmers might want to use threads.

In other words, is there no reason why "flow in method" solutions? and "method on stream?" must be connected. You can use "thread in method" if there are performance benefits to it, but it shouldn't affect the caller. (They should just be able to call the method and return the return value back without worrying about whether you are using internal threads).

, , , . , - , " ". " ", " " - + , .

Now that I am talking about how you build the library, in reality you are probably just building code for your own use. But regardless, the same principles apply. If you want to use threads to improve performance, it is better to encapsulate the use of threads behind an interface and make it so the rest of the program doesn't know or care if the XYZ module is using threads or not. At the same time, it is best that each module is thread safe, so callers can decide whether to use threads or not.

0


source







All Articles