While Loops: The Repeating Guard

While Loops: The Repeating Guard in Java: A boat has a bilge pump wired to a float switch. The switch has no idea how long the pump should run or how many…

The Analogy: The Bilge Pump And The Float Switch

A boat has a bilge pump wired to a float switch. The switch has no idea how long the pump should run or how many strokes it should make. It asks exactly one question -- is the water above this line? -- and while the answer is yes, the pump runs. The moment the answer becomes no, the pump stops. Nobody ever tells it a number.

The order of operations matters more than it looks. The switch is checked before the pump is energised, which means that on a dry boat the pump never runs at all, not even once. There is a different fitting on the market, a timed test cycle, which runs the pump first and asks the switch afterwards, so it always runs at least one stroke even on a dry day. Java ships both: while asks first, do-while runs first.

The whole arrangement rests on an assumption that nobody writes on the wiring diagram: the pump has to actually lower the water. A pump with a blocked outlet satisfies its own switch forever. It draws current, makes noise, and achieves nothing, and the switch is not lying -- the water really is still above the line. This is the infinite loop, and it is almost never a fault in the condition. It is a fault in the body, in the thing that was supposed to move the state toward the exit.

The failures follow from that. A switch that has stuck closed is a condition that reads something the body never changes. A pump wired past the switch is a continue that jumps over the line that was doing the work. And the quietest failure of all is a switch mounted lower than the pump can ever drain to: an exit condition that was unreachable from the moment the boat was fitted out, so the loop was always going to run until something else stopped it.


Syntax or Core Structure

while evaluates its condition, runs the body if it was true, and repeats. do-while runs the body, then evaluates. The difference is only ever visible on the first pass.

public class Bilge {
    public static void main(String[] args) {
        int litres = 5;
        while (litres > 0) {
            System.out.println("pumping  " + litres);
            litres--;
        }
        System.out.println("stopped  " + litres);

        int dry = 0;
        while (dry > 0) {
            System.out.println("never    reached");
        }
        System.out.println("skipped  " + dry);

        int test = 0;
        do {
            System.out.println("testing  " + test);
            test++;
        } while (test < 0);
        System.out.println("ran once " + test);
    }
}

Output:

pumping  5
pumping  4
pumping  3
pumping  2
pumping  1
stopped  0
skipped  0
testing  0
ran once 1

The second loop produces no output at all, because 0 > 0 is false on the first check and the body is never entered. The third loop produces one line despite test < 0 being false, because do-while has already run the body by the time it looks. Note also the semicolon after while (test < 0); -- it is required in a do-while and forbidden after a plain while, and swapping them is a compile error rather than a silent bug, which is a small mercy.


Technical Depth: Where The Three Parts Of A Loop Go When You Write while

Initialise, test, advance

Every counted loop has the same three parts. A for loop puts them on one line where they can be checked at a glance. A while loop scatters them, and that scattering is the source of almost every bug in this lesson.

PartIn a for loopIn a while loopIf you get it wrong
initialisethe first clausea line above the loopcompile error, or a stale value from an earlier loop
testthe second clauseinside the parenthesesthe loop never starts, or never stops
advancethe third clausesomewhere in the bodyinfinite loop, and nothing tells you

The for loop is not a better loop; it is the same loop with the three parts collected in one place. Use while when the number of passes is not knowable before the first pass, and for when it is.

The condition is re-read on every pass, left to right

int[] readings = { 4, 3, 0, 7 };
int i = 0;
int total = 0;

while (i < readings.length && readings[i] != 0) {
    total += readings[i];
    i++;
}

System.out.println("stopped at " + i);
System.out.println("total      " + total);

Output:

stopped at 2
total      7

The order of the two tests is load-bearing. i < readings.length has to come first, because && only evaluates the right-hand side when the left is true, and that is what stops readings[i] from being asked for element 4 of a four-element array. Written the other way round -- readings[i] != 0 && i < readings.length -- this loop throws ArrayIndexOutOfBoundsException the moment it walks off the end, and it throws it on the very input the second test was added to handle.

Two conditions that will never become false

double x = 0.0;
int passes = 0;

while (x != 1.0 && passes < 10) {
    x += 0.1;
    passes++;
}

System.out.println("passes     " + passes);
System.out.println("reached 1  " + (x == 1.0));
System.out.println("close      " + (Math.abs(x - 1.0) < 1e-9));

Output:

passes     10
reached 1  false
close      true

Ten additions of 0.1 do not produce 1.0. They produce a number about one part in ten thousand million million short of it, because 0.1 has no exact representation in binary and each addition rounds. Without passes < 10 in the condition, that loop runs forever: the counter sails straight past its target and keeps going, and != never gets its moment. Never use == or != on floating point in a loop condition. Count in integers and divide at the end, or compare against a tolerance as the third line does.

A continue that jumps over the advance

int n = 0;
int seen = 0;
int spins = 0;

while (n < 5 && spins < 20) {
    spins++;
    if (n == 2) {
        continue;
    }
    seen++;
    n++;
}

System.out.println("seen       " + seen);
System.out.println("spins      " + spins);
System.out.println("stuck at   " + n);

Output:

seen       2
spins      20
stuck at   2

That loop is broken on purpose, and the output is the shape of the bug rather than a hang. continue jumps to the condition, not to the end of the body, so n++ is skipped and n sits at 2 forever. In a for loop the advance clause still runs on continue, which is exactly why this mistake is a while speciality.

The spins counter is the technique worth taking away. Adding a bounded second test to the condition turns "the program hangs and somebody restarts the container" into "the program stops, and the printed counter says the loop never converged". It costs one int and it is the difference between a diagnosable failure and a mystery.


Real World Example: A Paginated Fetch That Has To Know When To Stop

A remote endpoint hands back at most three records per request and gives you no total. You cannot write a for loop over this, because the number of requests is not knowable until the last request comes back short. This is the case while exists for.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

public class Pager {

    private static final int PAGE = 3;

    private static final List<String> SOURCE = Arrays.asList(
            "d-101", "d-102", "d-103", "d-104",
            "d-105", "d-106", "d-107", "d-108");

    // Stands in for one HTTP call. Returns at most PAGE records,
    // and an empty list once the offset is past the end.
    static List<String> page(int offset) {
        if (offset >= SOURCE.size()) {
            return new ArrayList<String>();
        }
        int end = Math.min(offset + PAGE, SOURCE.size());
        return new ArrayList<String>(SOURCE.subList(offset, end));
    }

    public static void main(String[] args) {
        List<String> collected = new ArrayList<String>();
        int offset = 0;
        int requests = 0;
        int spins = 0;
        boolean more = true;

        while (more && spins < 50) {
            spins++;
            List<String> batch = page(offset);
            requests++;
            collected.addAll(batch);
            offset += batch.size();
            more = batch.size() == PAGE;
            System.out.println(String.format(Locale.ROOT,
                    "request %d  got %d  offset %d  more %s",
                    requests, batch.size(), offset, more));
        }

        System.out.println("requests   " + requests);
        System.out.println("collected  " + collected.size());
        System.out.println("first      " + collected.get(0));
        System.out.println("last       " + collected.get(collected.size() - 1));
        System.out.println("spins left " + (50 - spins));
        System.out.println("complete   " + !more);
    }
}

Output:

request 1  got 3  offset 3  more true
request 2  got 3  offset 6  more true
request 3  got 2  offset 8  more false
requests   3
collected  8
first      d-101
last       d-108
spins left 47
complete   true

The termination signal in this program comes out of the data, not out of a count. Nothing anywhere knows there are eight records. The loop keeps asking for the next page and stops when a page comes back short, which is the only evidence available that there is nothing left. That is the shape of every cursor, every directory walk, every socket read and every message queue drain you will ever write: the loop condition is a question about the last answer, not about a number you worked out in advance.

more = batch.size() == PAGE is the whole protocol, and it is worth being precise about what it assumes. A full page means "there may be more"; a short page means "that was the end". When the record count is an exact multiple of the page size, this costs one extra request that comes back empty -- with nine records the loop would run four times and the fourth batch would be size 0. That is correct but wasteful, and it is why real APIs return a nextCursor that is null on the last page: an explicit end marker beats inferring the end from a length.

The spins < 50 clause never fires here, and spins left 47 proves it. It is there for the day the endpoint changes and starts returning a full page forever. Note that complete is printed separately from requests: the loop can end for two entirely different reasons, and a caller that only sees the collected list cannot tell "I read everything" from "I gave up after fifty requests". Any loop with a guard needs to report which exit it took, or the guard has quietly converted a hang into silent data loss.

The honest limits. Offset pagination is wrong under concurrent writes: if a record is inserted before offset 3 between the first and second request, the record that was at index 2 shifts to index 3 and gets returned twice, and if one is deleted a record is skipped entirely and no error is raised anywhere. Keyset pagination -- "give me the 3 records after id d-103" -- does not have this failure mode, and this program should use it. Second, collected.get(0) throws IndexOutOfBoundsException on an empty source, which is a working program that crashes on the completely ordinary case of no data. Third, the guard silently truncates: a source with a thousand records yields 150 and a complete false that nobody is required to look at. A guard that logs and throws is honest; a guard that returns a short list and a flag is a trap.


Common Mistakes

  1. Forgetting the advance. while (litres > 0) { pump(); } never changes litres, so it runs until the process is killed. When a while loop hangs, look for the missing increment in the body before you re-read the condition -- the condition is almost always right.
  1. Initialising the counter inside the body. while (i < 5) { int i = 0; ... } will not compile, but the same mistake with an existing variable -- assigning i = 0 as the first statement of the body -- compiles cleanly and loops forever. The initialise step belongs above the loop, and it must run exactly once.
  1. Testing floating point with != or ==. while (x != 1.0) where x grows by 0.1 never terminates, because ten additions of 0.1 produce a value slightly under 1.0. Count passes with an int, or compare against a tolerance.
  1. Putting the bounds test second in a && chain. while (readings[i] != 0 && i < readings.length) throws ArrayIndexOutOfBoundsException, because the array is indexed before the length is checked. The guard has to be the left operand for short-circuiting to protect anything.
  1. Using continue in a while loop that advances at the bottom. continue jumps to the condition, so it skips the increment and the loop sticks. Either advance before the continue can be reached, or use a for loop, whose advance clause still runs.
  1. A stray semicolon after the condition. while (litres > 0); is a complete statement with an empty body, and the block that follows it runs once, after the loop has already hung. The compiler accepts this without a murmur.
  1. Expecting do-while to check first. do { send(batch); } while (!batch.isEmpty()); sends an empty batch before discovering the list is empty. do-while guarantees one pass, so anything inside it must be safe to do unconditionally.
  1. Reading the counter after the loop as if it were the last valid index. After while (i < readings.length) completes normally, i equals readings.length -- one past the end. readings[i] throws. If the loop can exit early, i is the index it stopped at; if it ran to completion, it is not an index at all.
  1. Trusting an IO-driven loop to terminate. A loop whose exit depends on a server, a file, a queue or a user has no guaranteed end. Without a bounded second test in the condition, a single misbehaving dependency turns into a pegged CPU and a service that never restarts itself.

Best Practices

  • Choose for when the pass count is knowable and while when it is not. A for loop puts initialise, test and advance where one glance covers all three; a while loop earns its scattering only when the number of passes genuinely depends on what the loop discovers.
  • Advance in exactly one place, as the last statement of the body. Two increments on different branches drift apart the first time someone adds a third branch and forgets one.
  • Give any loop that waits on something outside your process a bounded second test, and print the remaining budget. while (more && spins < 50) plus spins left 47 converts a hang into a diagnosable stop, for the price of one int.
  • Report which exit the loop took. If the loop can end because the work finished or because a guard fired, the caller needs a flag that distinguishes them. Otherwise the guard silently turns truncated results into apparently-complete ones.
  • Order && operands so the guarding test comes first. Bounds checks, null checks and cheap tests belong on the left; the expensive or dangerous operand belongs on the right, where short-circuiting protects it.
  • Count in integers and convert once at the end. Accumulating 0.1 per pass produces a counter that never equals its target; counting to 10 and dividing by 10 produces one that does.
  • Keep the body short enough that the condition and the advance are visible together. Extract the work into a method. A twenty-line body with the increment on line eighteen is where the infinite loops live.
  • Name a compound condition. boolean more = batch.size() == PAGE; reads as intent; the same expression inlined into the while parentheses reads as arithmetic, and it invites someone to change the page size without noticing what else depends on it.

Practice Exercises

  1. The Blocked Outlet. Take the bilge program from the Syntax section and break it: remove litres-- from the body. Do not run it yet. Add a spins counter and a spins < 100 clause to the condition first, then run it and print litres, spins and whether the loop ended because the boat was dry or because the guard fired. Then fix the advance and confirm the guard reports slack rather than firing. The habit you are building is adding the guard before running the loop, not after it hangs.
  1. The Exact Page. Change Pager's SOURCE to hold exactly nine records and run it. Explain the fourth request in the output and say whether collected is still correct. Then add an explicit end marker: have page return a small class holding both the batch and a nextOffset that is -1 on the last page, drive the loop from that marker instead of from batch.size() == PAGE, and show that the nine-record case now takes three requests.
  1. The Keyset Rewrite. Replace page(int offset) with pageAfter(String lastId), which returns the first three records whose id sorts after lastId (pass null for the first call). Drive the loop with the id of the last record you received. Then write the interference test that justifies the change: fetch page one, insert a record that sorts before d-103, fetch page two, and print the collected ids. Run the same test against the offset version and show the duplicated id in one output and not the other.