I am to download data from the server, with a maximum of 3 attempts if the download fails.
public class DownloadFile {
private boolean isSuccessful;
public DownloadFile() {
int attempt = 0;
while(!isSuccessful && (attempt++ < 3)) {
DownloadFileThread.start();
while (DownloadFileThread.isAlive());
}
}
private Thread DownloadFileThread = new Thread() {
public void run() {
try {
// download file from server
isSuccessful = true;
} catch (Exception e) {
isSuccessful = false;
}
}
}
}
As you can see in the above example, I have an empty while loop in (what would be) line 10 to force guarantee isSuccessful is assignment a value based on the outcome of the DownloadFileThread before checking the condition in the while loop again.
Is it considered bad practice to do such a thing? Is there better approach or a correct way to do this?
While the above code does produce a valid result, I am not exactly proud of the code I have written...
Yes, in this case it is a bad practice, because Java offers better mechanisms to wait for completion of a thread: Thread.join(), or consider using more modern features like CompletableFuture or an ExecutorService that allows you to wait for a task to complete.
Using an empty loop to wait will consume a lot of CPU power unnecessarily, which might mean other tasks on your system will perform slower than they could otherwise.
Not necessarily, but in this case this is a busy wait which is bad practice especially in multi-threaded programs. It keeps the CPU busy and in your case interferes with DownloadFileThread.
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