Assaf
Assaf

Reputation: 43

What is the best way to Handle multiple threads in one class

I want to create a class that some of its methods on separate threads, and I'm not what us the best way to achieve that.

I've thought about three options:

  1. Anonymous class for each method - On the one hand it's easier to implement, on the other hand it's less readable, and more difficult to maintain if in the future I'll decide not to run on a separate thread for a specific method.

  2. implementing runnable and using a switch case statement - On the one hand it's more readable, and i can code the class such that it will be more maintainable in some if it's aspects. But, it will have a large switch case in the run method

  3. Divide the class into multiple classes, and put each method that requires a separate thread in a separate class. - It doesn't have any of the disadvantages the previous options have, but it might lead to to many classes with only one method (run). Also, it's still has some mainatinability issues

  4. Create a special class for each thread, and there run all necessary methods from all classes. - breaks SRP?

Thank you for your help

Upvotes: 1

Views: 720

Answers (1)

Gray
Gray

Reputation: 116858

I want to create a class that some of its methods on separate threads, and I'm not what us the best way to achieve that.

Anonymous class for each method

I agree with your assessment. This will make the code less readable for sure. Not an immediate win. When it comes down to it, anonymous classes are true classes just done inline. I'd pay the extra characters in your Java file and create sub-classes. See below.

implementing runnable and using a switch case statement

This has certainly been done before and may be necessary if the multiple methods share a lot of data and methods. But I think that the below answer is better.

Divide the class into multiple classes

I think that this is the right thing to do. Each of your classes can implement Runnable so you can submit them to a thread-pool easily. If the methods need to share data and other methods then you could make the classes be subclasses in a larger class and make sure they are not static.

Create a special class for each thread

Not sure what "special" means here.

Upvotes: 1

Related Questions