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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With