flxh
flxh

Reputation: 565

Is this an acceptable "recursive" concurrency design

I want to process some data in parallel worker threads. But instead of a parent thread that checks if one worker thread has finished and then assigning a new task, I want the threads to load the data themselfs and to restart themselfes again.

Now this is what I came up with:

public class MainApp {

ExecutorService executor;


public synchronized void runNewWorkerThread(){

    //load the data to be processed in the threads from a file 

    executor.submit(()->{
        try{
            // process data (unstable)
        }catch(Exception e){
            //catch and log exception
        }finally{
            runNewWorkerThread();
        }

    });


}

}

now this recursivly restarts the worker threads.Is this an acceptable design, or should I rather keep the worker threads alive by doing some kind of a loop inside the runnable?

If this is an acceptable design, which ExecutorService would you reccomend me to use, and why ?

Thanks a lot, Flo

Edit: The number of Threads started is fixed, because in the threads a fixed number of real devices is automated. However there is one single list the threads need to load their data from,sequentially.

Upvotes: 1

Views: 113

Answers (1)

Stefan Dollase
Stefan Dollase

Reputation: 4620

I think your code is fine. Also, you should not run into a StackOverflowException, since you do not call the method runNewWorkerThread directly. You just submit the code to call the runNewWorkerThread to the ExecutorService and the submit function call will return pretty much instantly (depending on the implementation).

Be sure to start the worker properly. If you want e.g. five threads to run in parallel, you need to call the runNewWorkerThread method five times, because every call to runNewWorkerThread will start only exactly one new runNewWorkerThread after it is finished. Also, you should only have one MainApp object, to ensure the synchronized keyword really synchronizes all load operations.


Update

If you use e.g. the newFixedThreadPool you can be sure to not run into a StackOverflowException, because this ExecutorService only runs a fixed number of threads at a time. That means, that it will only execute another submitted task, after one of the other task is finished. Because the other task is finished, it must have left the runNewWorkerThread method. I hope this is clear enough?

Upvotes: 1

Related Questions