Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an empty while loop considered bad practice?

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...

like image 322
El Sushiboi Avatar asked Jul 16 '26 23:07

El Sushiboi


2 Answers

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.

like image 117
Mark Rotteveel Avatar answered Jul 19 '26 12:07

Mark Rotteveel


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.

like image 42
Jonathan Rosenne Avatar answered Jul 19 '26 13:07

Jonathan Rosenne