Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Thread within a thread - good practice? [duplicate]

Is it good practice to start a thread within a thread? I have searched around but have not found much information.

I have a TimerTask which gets a list of users every day at a certain time. I then want to get some data about the user, but this requires user input. Because it requires user input, I don't want my TimerTask thread to be blocked in the case of users not responding. For example, the first user in the list may not respond in X amount of time, I don't want to wait X amount of time until I ask the second user for their data, and so on. So within my TimerTask, I create and start a new Thread to get the data. This way, in Y amount of time, if i have recieved some data (but not all) I can still do other things instead of waiting for every one to complete.

Is it good practice to do the above? Are there any better solutions?

Here is some psudeo code which may help you understand.

class UserThread extends TimerTask {

        @Override
        public void run() {
            log.debug("Get a list of members!");
            List<String> users = userManager.getUsers();
            retrieveInitialData(users);
        }

        public void retrieveInitialData(List<String> users) {
            for(String user : users) {
                new Thread(new GetData(user)).start();
            }
        }

        addToSuccessList(String user) {
            synchronized(successList) {
                successList.add(user);
            }
        }

        addToFailureList(String user) {
            synchronized(failureList) {
                failureList.add(user);
            }
        }

        class GetData extends Thread {

            String userID;

            public GetData(String user) {
            this.userID = user;
            }

            public void run() {
            try {
                dataManager.getData(user);
                addToSuccessList(user);
            } catch(Execption e) {
                addToFailureList(user);
            }

        }
like image 397
Stu Whyte Avatar asked Feb 19 '14 14:02

Stu Whyte


2 Answers

A better approach would be to use a ThreadPool and a ScheduledExecutorService. Starting a thread from a thread is not inherently bad (after all everything runs inside a thread so you need to do that somewhere!) but may indicate a flaw in your design.

like image 126
Tim B Avatar answered Nov 14 '22 21:11

Tim B


In Java all threads are owned by the process, and it doesn't matter from where they are started. So there's nothing wrong with your code.

like image 25
Joatin Avatar answered Nov 14 '22 23:11

Joatin