Programming Paradigms · Lab 7 · session 7: multi-threading

Threads: Four Structures and a Mini Ray Tracer

The lab has two halves. The warm-up is four Java classes to finish: a counter, a group of worker threads, a bounded buffer and a barrier. Each class is a file with holes, a contract that says what the class must do, and a check program that tests it. The quest is a mini ray tracer, made multi-threaded with those four classes.

Three properties recur. Mutual exclusion: no two threads are inside the code that changes shared data at the same time. Ordering: a thread acts only after another has acted. Visibility: a write on one thread is seen by a read on another. A lock, an atomic instruction and a copy per thread give mutual exclusion. A join, a barrier and a monitor's wait give ordering, and visibility with it. A volatile write gives visibility only.

The files

The lab's files are in the course's repository on GitHub, leon-gondelman/pp26, in the folder labs/lab7-threads. The first time, git clone copies the whole repository; afterwards, git pull inside the copy brings each new lab. The lab needs the JDK of session 1.

Shell
git clone https://github.com/leon-gondelman/pp26.git     # the first time
cd pp26
git pull                                                   # every later time
cd labs/lab7-threads

In the folder: warmup/, the warm-up's classes and their checks; quest/, the ray tracer; rules/, the rules sheet cited by number on this page; primitives.pdf, the questions on paper of the last section.

Warm-up: four Java classes

Each part below is one class in warmup/. The way through a part: read the contract, fill the holes marked TODO n in the file, compile, and run the class's check until every line says pass. Two lines are meant otherwise: the info line of CounterCheck, the lost update forced, and the FAIL of CounterCheck racy. A hole holds throw todo(n) until it is written; three holes hold a wrong line instead, and their exercise says so: TODO 1 and TODO 2 of BoundedBuffer, each wait written with an if, and TODO 4 of Workers, the flag declared plain. A FAIL names the clause of the contract that failed.

Warm-up walkthroughPart 1's LockedCounter filled and checked; part 2's Workers checked with the flag plain, then volatile.2:40 · 10 steps · no sound
PartFileTo writeCheck
1warmup/LockedCounter.java, warmup/AtomicCounter.java, warmup/PerWorkerCounter.javathree correct counters: with a lock (block 1 of the lecture), with an atomic and with one slot per thread (block 2)CounterCheck
2warmup/Workers.javastart, join and stop of n threadsWorkersCheck
3warmup/BoundedBuffer.javathe two waits of put and take, as loopsBufferCheck
4 (extension)warmup/Barrier.javaawait, reusable over roundsBarrierCheck

The lab covers parts 1 to 3; part 4 is an extension. Parts 3 and 4 rest on the monitor's wait, which the lecture leaves to the appendix of block 1's slides, Condition synchronization. The checks run under heavy contention, and still a check can show a bug, never prove there is none (rule 8 of the rules sheet). The commands, from labs/lab7-threads:

Shell
cd warmup
javac -d out *.java
java -cp out CounterCheck locked      # or racy, atomic, perworker
java -cp out WorkersCheck
java -cp out BufferCheck
java -cp out BarrierCheck

Part 1: The counter, three waysat the keyboard

RacyCounter loses adds. The exercise writes the lecture's three repairs behind one interface. The lock is in block 1 of the lecture; the atomic and the count per thread are in block 2 (examples 6 and 8), so after block 1 alone, LockedCounter comes first.

Exercise 1

Given the interface Counter, RacyCounter, and the classes LockedCounter, AtomicCounter and PerWorkerCounter with their holes, write the three: LockedCounter with synchronized on both methods; AtomicCounter with an AtomicLong and incrementAndGet; PerWorkerCounter with an AtomicLongArray, one slot per worker, written only by its owner and summed by get(); of the array's methods, incrementAndGet(i), get(i) and length() suffice. The slots are atomic so that a read during the run sees the writes; a plain array would be correct only after the join. Before running each class, write a prediction in the comment above it: the exact total, less, more, or it depends on the run. Optional: a fourth counter on the lecture's spin lock, AtomicBoolean.getAndSet.

Javawarmup/Counter.java
public interface Counter {
  void add(int worker);
  long get();
}
Javawarmup/RacyCounter.java
public final class RacyCounter implements Counter {
  private long n = 0;                       // shared by every thread, protected by nothing

  public void add(int worker) { n++; }
  public long get() { return n; }
}
Javawarmup/LockedCounter.java
public final class LockedCounter implements Counter {
  static RuntimeException todo(int n) { return new UnsupportedOperationException("TODO " + n); }   // a hole: write the code in place of throw todo(n)
  private long n = 0;                       // guarded by this

  public void add(int worker) {
    // TODO 1: the increment under the lock
    throw todo(1);
  }

  public long get() {
    // TODO 2: the read under the same lock
    throw todo(2);
  }
}
Javawarmup/AtomicCounter.java
public final class AtomicCounter implements Counter {
  static RuntimeException todo(int n) { return new UnsupportedOperationException("TODO " + n); }   // a hole: write the code in place of throw todo(n)
  private final AtomicLong n = new AtomicLong(0);

  public void add(int worker) {
    // TODO 3: the increment as one instruction
    throw todo(3);
  }

  public long get() {
    // TODO 4: the read
    throw todo(4);
  }
}
Javawarmup/PerWorkerCounter.java
public final class PerWorkerCounter implements Counter {
  static RuntimeException todo(int n) { return new UnsupportedOperationException("TODO " + n); }   // a hole: write the code in place of throw todo(n)
  private final AtomicLongArray slots;      // slot i is written by worker i only

  public PerWorkerCounter(int workers) { slots = new AtomicLongArray(workers); }

  public void add(int worker) {
    // TODO 5: the worker's own slot, one more
    throw todo(5);
  }

  public long get() {
    // TODO 6: the sum of the slots, read one after another
    throw todo(6);
  }

  public long get(int worker) { return slots.get(worker); }
}

The check: java -cp out CounterCheck racy, then locked, atomic, perworker. The check has two halves. The first forces one lost update: two threads run the three steps of n++ with a barrier between the read and the write, so both read the same value; the output shows the two reads, the two writes and the lost add. The second runs twelve threads that add to the named counter while a reader calls get() repeatedly. After the join the total must equal the number of adds; every read during the run must lie within the contract's bounds and never decrease.

Part 2: Workers: start, join, stopat the keyboard

n threads running one indexed task, a join, and a stop flag.

Exercise 2

Given the class Workers, with its threads kept in an array, write start, join and stop, and leave the flag plain, as declared. A lambda captures only an effectively final local variable, so start copies the loop index into a final local, final int id = i;, before new Thread(() -> task.accept(id)). A task reads the flag through the object:

Java
Workers w = new Workers(n);
w.start(i -> { while (!w.stopped()) work(i); });
w.stop();
w.join();
Javawarmup/Workers.java
public final class Workers {
  static RuntimeException todo(int n) { return new UnsupportedOperationException("TODO " + n); }   // a hole: write the code in place of throw todo(n)
  private final Thread[] threads;
  private boolean started = false;
  // TODO 4: plain for the first run of the check; then volatile
  private boolean stopFlag = false;

  public Workers(int n) { threads = new Thread[n]; }

  public void start(IntConsumer task) {
    // TODO 1: one thread per index, each running task.accept(i) once; a second start throws
    // IllegalStateException
    throw todo(1);
  }

  public void join() throws InterruptedException {
    // TODO 2: return only when every thread has ended
    throw todo(2);
  }

  public void stop() {
    // TODO 3: the flag
    throw todo(3);
  }

  public boolean stopped() { return stopFlag; }
}

The check: java -cp out WorkersCheck, three lines. First: each index runs once, on its own thread, and every slot the workers wrote is present after the join. Second: a second start throws IllegalStateException. Third: workers spin on an empty loop that tests only the flag; the check calls stop, waits until a deadline, and reports which workers stopped. The verdict comes from the flag's declaration, not from the run: a plain flag fails, because no rule requires a plain read to see another thread's write, and the compiler may read the field once and keep it in a register (rule 9). On the course's JDK, the compiled loop does so and never ends. Then declare the flag volatile (TODO 4), which forbids that, and run again: every worker stops. Question 6 of the questions on paper (primitives.pdf) is the same case, as practice.

Part 3: The bounded buffer as a monitorat the keyboard

Example 5 of the slides, in the appendix of block 1, Condition synchronization, which this part assumes. The same class is the one-lock queue that the mini-project starts from.

Exercise 3

Given the ring of slots under the object's lock, with put and take testing each wait condition once with an if, write the two waits as loops, with notifyAll (TODO 1, TODO 2). The end marker is a value the client reserves, BufferCheck.END in the check and Frame.END in the quest; the consumer loop that stops on it is given. Run the check first with the ifs and read the report, then with the loops.

Javawarmup/BoundedBuffer.java
public final class BoundedBuffer<T> {
  private final Object[] slots;             // the ring; guarded by this
  private int head = 0, tail = 0, count = 0;

  public BoundedBuffer(int capacity) { slots = new Object[capacity]; }

  public synchronized void put(T x) throws InterruptedException {
    // TODO 1: wait while the buffer is full, in a loop (rule 4)
    if (count == slots.length) wait();
    slots[tail] = x;
    tail = (tail + 1) % slots.length;
    count++;
    notifyAll();                            // wake every waiting thread (rule 5)
  }

  @SuppressWarnings("unchecked")
  public synchronized T take() throws InterruptedException {
    // TODO 2: wait while the buffer is empty, in a loop (rule 4)
    if (count == 0) wait();
    T x = (T) slots[head];
    slots[head] = null;
    head = (head + 1) % slots.length;
    count--;
    notifyAll();
    return x;
  }
}

The check: java -cp out BufferCheck: many producers and one consumer that pauses at intervals, so that producers queue at the full buffer. The main thread joins the producers, then puts the end marker. Each put records the order of insertion under the buffer's lock; the consumer must take the items in that order, each once. With the ifs, items are lost, and the report names the wait. With one consumer, the if of take (TODO 2) fails only on a wake-up without cause, which a normal run does not produce, so its loop is required by the contract, not by the check. Then, as an experiment, replace notifyAll by notify in both methods and run: the program may hang, when a wake-up the consumer needed reaches a producer. The check waits 20 seconds from the start of the run, then reports a hang with the waiting threads. After the experiment, notifyAll goes back into both methods.

Part 4: The barrierextensionat the keyboard

Ordering over a whole phase, built on the monitor. Part 5 of the quest uses it.

Exercise 4

Given Barrier with its count of parties, its action and an empty await(), write await() in two steps. First for one round: count the arrivals under the lock; every party but the last waits; the last runs the action, resets the count and wakes the others. Then make it reusable with a round number: a party waits while the round it arrived in is still current. Without the round number, the reset makes a slow waiter's condition true again, so it waits for ever, and a fast party that arrives for the next round corrupts the count. An interrupted waiting party and an action that throws break the barrier, as the contract states.

Javawarmup/Barrier.java
public final class Barrier {
  static RuntimeException todo(int n) { return new UnsupportedOperationException("TODO " + n); }   // a hole: write the code in place of throw todo(n)
  public interface Action { void run() throws InterruptedException; }

  private final int parties;
  private final Action action;
  private int waiting = 0;                  // arrivals in this round; guarded by this
  private long round = 0;                   // the current round; guarded by this
  private boolean broken = false;           // guarded by this

  public Barrier(int parties, Action action) {
    this.parties = parties;
    this.action = action;
  }

  public synchronized void await() throws InterruptedException, BrokenBarrierException {
    // TODO 1: count the arrival; the last runs the action, resets, wakes; the rest wait
    throw todo(1);
  }
}

The check: java -cp out BarrierCheck, two lines. First: a few parties run many rounds at full speed, with an action that counts the rounds; the check records any party that passes before all have arrived, requires the action to run once per round, by the last arrival, and reports a hang at a deadline with the waiting parties. Second: one waiting party is interrupted; it leaves with InterruptedException, the other party and a later arrival with BrokenBarrierException. The check injects no wake-up without cause, so the rounds line cannot catch a single if (...) wait(): the loop is required by rule 4, not by the check.

From the warm-up to the quest

The quest's path uses Counter and Workers: the progress bar and the tiles per worker on the counter, every render and the explorer's restart on the workers. Part 5, an extension, uses Barrier and BoundedBuffer. Each structure has a finished copy in quest/given/, taken with --given counter, --given workers and so on, so that an unfinished structure blocks nothing. After the lab, the mini-project starts from BoundedBuffer as its one-lock queue.

Quest: A Mini Ray Tracer

The scene of scene.txt rendered by part 4: sixteen samples per pixel, soft shadows, one tone map
The scene of scene.txt rendered by part 4: sixteen samples per pixel, soft shadows, one tone map

The quest starts from a sequential ray tracer in Java. It reads a scene from a text file (spheres, cubes, a floor, lights, a camera) and writes a PNG with shadows and mirror reflections. Six parts make it multi-threaded with the warm-up's structures. Each part has two or three holes: which structure goes where, in what order, and one sentence on why. At the end the program renders in parallel with a correct progress bar, balances the work across threads, and restarts the render when the camera moves. The extensions add soft shadows from many samples per pixel, and a video of a turning cube.

Parts 1, 2, 3 and 6, in that order, are the path; they use Counter and Workers only. Parts 4 and 5 are extensions; part 5 uses Barrier and BoundedBuffer. The lab collects nothing.

The tracer itself, in quest/tracer/, is sealed. The program uses it through this interface only:

Java
Colour  Tracer.sample(Scene scene, int x, int y, Rng rng)   // one ray through pixel (x, y), jittered by rng; rng null: the pixel's centre, hard shadows
Rng     Rng.of(int x, int y, int sample)                     // the generator of sample s of pixel (x, y)
Scene   Scene.read(String file); scene.at(int frame)         // the scene of the file; the scene at that frame, an immutable value
Scene   scene.withCamera(Vec eye, Vec look); scene.width(); scene.height(); scene.samples(); scene.frames()
Picture new Picture(w, h); picture.set(x, y, colour); picture.write(file)   // the buffer and the PNG
Preview new Preview(file); preview.write(picture)            // the picture so far, to the same file, now and then
Frame   new Frame(k, w, h); frame.picture; Frame.END         // a frame of the video and the end marker

The warm-up's four structures, finished or not, go into quest/structures/; the skeletons compile. Then, from quest/:

Shell
cd quest
javac -d out *.java tracer/*.java structures/*.java
javac -d out/given given/*.java
java -cp out Render scene.txt
java -cp out Render scene.txt --part 1 --counter racy
java -cp out Check 1

A cannot find symbol for Counter, Scene or Picture when compiling means a folder is missing from the javac line: the quest compiles from *.java, tracer/*.java and structures/*.java together.

Render writes render.png. Its options: --part n, how far the program goes; --counter racy|locked|atomic|perworker, the counter the bar reads; --threads n; --out file; --given workers or --given counter,buffer, the finished copies in given/ in place of unfinished structures. Check n runs the check of part n. Each line says pass, FAIL or todo, and a FAIL names the file, the hole and the question to ask. Each check first tries the structures its part runs on, those of structures/: a fault there is named there, with the warm-up check that tests it, and the part's holes wait for it. As in the warm-up, a check can show a bug, never prove there is none (rule 8).

The parts accumulate in one Render.java; each part says which lines it replaces. The program rewrites the PNG at intervals during the render, and an image viewer that reloads a changed file (Preview on macOS, most viewers elsewhere) shows the picture grow.

Every command of the quest, from quest/, in the order of the parts. While the warm-up's structures are unfinished, each program and each check takes --given counter,workers,buffer,barrier at the end.

Shell
javac -d out *.java tracer/*.java structures/*.java
javac -d out/given given/*.java
java -cp out Render scene.txt                                  # part 0, no check
java -cp out Render scene.txt --part 1           ; java -cp out Check 1
java -cp out Render scene.txt --part 2 --counter perworker ; java -cp out Check 2
java -cp out Render scene.txt --part 3 --counter perworker ; java -cp out Check 3
java -cp out Explorer scene.txt                  ; java -cp out Check 6
java -cp out Render scene.txt --part 4 --counter perworker ; java -cp out Check 4
java -cp out Video scene.txt                     ; java -cp out Check 5
ffmpeg -framerate 24 -i frames/frame-%04d.png -pix_fmt yuv420p video.mp4
java -cp out Check all

The viewer

The viewer is the quest in one page of the browser: the picture as the program renders it, each part one click away, and the quest's holes as stations on a line. It compiles the quest's files on every save and runs the six checks, and a station fills when its part's check passes on it; a part opens when the line reaches it, its own holes still hollow, so their failure is seen first. A click on a station gives its task, what the check says, and a link back to this page. It runs the same programs as the terminal, nothing more. From quest/:

Shell
javac -d out/viewer viewer/Viewer.java
java -cp out/viewer Viewer

The page opens at http://localhost:8190/; Ctrl-C in the terminal ends the viewer. With --given, or the switch on the page, the checks and the parts take the finished copies of the structures in given/.

Quest walkthroughPart 1 filled, the viewer launched and part 1 run, then part 2 and its first hole.2:15 · 8 steps · no sound

Part 0: The sequential render

The need: java -cp out Render scene.txt renders on one thread: one sample per pixel, jagged edges, hard shadows, one front moving down the picture.

Given the program and scene.txt, change a colour or move a sphere and render again. This part has no hole and no check: its picture and its time are the baseline the other parts are compared with. The scene file has one object per line: a keyword, then key-value pairs. yaw is the rotation about the vertical axis in degrees, spin the rotation per frame. Part 4 reads samples and a light's radius (soft shadows), and needs tone mapping because light colours exceed 1; part 5 reads frames. The line marbles puts count small spheres on the floor, drawn from the seed, the same at every run. The tracer has no index of the objects: every ray is tested against every sphere, so the count sets how long a render takes, and a smaller count makes every part faster on a slower machine.

Textquest/scene.txt
# The scene of the quest. One object per line: a keyword, then key-value pairs.
# yaw is the rotation about the vertical axis in degrees, spin the degrees per frame;
# radius on a light gives soft shadows from part 4; a light's colour above 1 is what makes
# the tone map of part 4 needed. samples is read from part 4, frames from part 5. marbles is
# count small spheres strewn on the floor, drawn from the seed; every ray is tested against
# each of them, so the count sets how long a render takes.
settings  size 2560 1440  samples 16     frames 60
camera    eye 0 1.6 -7    look 0 0.6 0   fov 40
light     at -4 6 -3      colour 1.4 1.4 1.4   radius 0.8
light     at  5 4 -2      colour 0.4 0.4 0.5
light     at  0 3 -9      colour 0.25 0.22 0.2
plane     y 0             checker 0.85 0.85 0.85 / 0.15 0.15 0.15
sphere    at -1.8 1 0.5   radius 1       colour 0.9 0.3 0.2   mirror 0.3
cube      at  1.2 0.75 0  size 1.5       colour 0.2 0.4 0.9   mirror 0.6   yaw 20   spin 3
cube      at  3.5 0.5 2.5 size 1         mirror 0.9           yaw 45
sphere    at -4.5 0.5 3   radius 0.5     colour 0.95 0.8 0.2  mirror 0.2
sphere    at -3.2 0.4 4.5 radius 0.4     colour 0.3 0.8 0.4   mirror 0.5
sphere    at -0.6 0.35 3  radius 0.35    colour 0.9 0.9 0.9   mirror 0.9
sphere    at  5.5 0.6 6   radius 0.6     colour 0.6 0.3 0.8   mirror 0.4
sphere    at  1.5 0.3 -2.2 radius 0.3    colour 0.2 0.7 0.9   mirror 0.7
marbles   count 300       radius 0.08 0.22   x -10 10   z -1 18   seed 7
Javaquest/Render.java
  // ---- part 0: one thread, one front -----------------------------------------------------

  static void sequential(Scene scene, Counter counter, Picture picture) {
    for (int y = 0; y < scene.height(); y++) row(scene, y, picture, counter, 0);
  }

  /** One row of the picture, every pixel counted on the counter as worker i's. */
  static void row(Scene scene, int y, Picture picture, Counter counter, int worker) {
    for (int x = 0; x < scene.width(); x++) {
      picture.set(x, y, Tracer.sample(scene, x, y, null));
      counter.add(worker);
    }
  }
Shell
java -cp out Render scene.txt

Gives: The baseline, and its time: 10.7 s at 2560 × 1440 on a laptop with twelve processors (an Apple M4 Pro), the laptop of every time given below. Each pixel is one call of Tracer.sample, written by picture.set and counted on the counter the bar reads.

Part 1: Workers

The need: The machine has Runtime.getRuntime().availableProcessors() processors, and one of them does all the work.

Given Render.java with the sequential loop over rows and the picture buffer, the bar on the racy Counter, the warm-up's Workers, and the band loop with two holes, write in bands: worker i's band of rows, computed from i, the bands covering every row and the last one taking the remainder, each row rendered by row(scene, y, picture, counter, i); then the join before the PNG is written. Then write, as a comment at hole 1, why no two workers write the same pixel.

For example, 10 rows on 3 workers are the bands of rows 0 to 2, 3 to 5 and 6 to 9: the last band takes the row left over. start returns at once, the workers still rendering, and the PNG is written from the picture as it is when bands returns; the join is what makes the main thread wait for every band first.

As given, the PNG is written at once, grey. With the bands and without the join, it is written with some bands still grey. With both, every band advances at once and the render finishes several times sooner (2.1 s on the laptop of part 0). The bar, still on the racy counter, stops short of 100 %; part 2 repairs it.

From this part on, the bar's thread reads the picture buffer for the preview while the workers write it. This data race on plain ints is accepted: an int is written whole, a stale pixel only delays the preview, nothing is computed from it, and the final PNG is written after the join. The last question of the lab asks for it.

The bands without the join: the PNG written when about a fifth of the pixels were done
The bands without the join: the PNG written when about a fifth of the pixels were done
Javaquest/Render.java
  // ---- parts 1 and 2: workers over bands of rows -----------------------------------------

  /** The picture cut into one band of rows per worker, each worker over its own band. */
  static void bands(Scene scene, int threads, Counter counter, Picture picture) throws InterruptedException {
    int h = scene.height();
    Workers w = new Workers(threads);
    w.start(i -> {
      // TODO 1: worker i renders its own band of rows with row(scene, y, picture, counter, i):
      // the bands cover every row, the last takes the remainder. Then write here why no two
      // workers write the same pixel.
      
    });
    // TODO 2: nothing waits for the workers here, and the PNG is written at once.
    
  }
  • hole 1: the band's bounds from the worker's index, and the loop over its rows; then the sentence: no two workers write the same pixel, because …
  • hole 2: the join, before the PNG is written.
Shell
java -cp out Render scene.txt --part 1
java -cp out Check 1

The check: the picture equals the sequential one, pixel for pixel. Rows left grey when render returns are looked at again once the workers have stopped writing, so that the two holes are told apart. Failures: rows 0 to 179 are unrendered, even once the workers have stopped writing: does every row belong to a band, the last taking the remainder? (Render.java, hole 1); rows 0 to 179 are unrendered when render returned, and the picture was whole only later: was every worker joined before the PNG was written? (Render.java, hole 2)

Gives: Ownership as the first technique. The picture buffer is shared and unprotected, and correct because each pixel has exactly one writer and no invariant spans two pixels. The join publishes the workers' writes to the main thread (question 1 of the primitives' page).

Part 2: The progress bar

The need: In part 1 the bar stops short of 100 %: twelve threads add to a racy counter while a thirteenth reads it.

Given the bar's loop in Bar.java, which reads the counter at intervals, the option --counter racy | locked | atomic | perworker, and Render.counter, which returns the racy counter for every option, write the choice: one implementation per option, the warm-up's three beside the racy one. Run the bar with each, then write at the hole which counter the bar should use and why, from the contract: what each guarantees, what each costs.

Javaquest/Render.java
  /** The counter the --counter flag names, one of racy, locked, atomic, perworker. */
  static Counter counter(String kind, int workers) {
    // TODO 3: the counter the flag names: "racy" is new RacyCounter(), "locked", "atomic" and
    // "perworker" (which takes the number of workers) are the warm-up's three; until
    // then every flag gives the racy one. Then run the bar on each of the four, and write
    // here which one the bar keeps, and why, from the contract: what does it guarantee,
    // what does it cost?
    return new RacyCounter();
    
  }
Javaquest/Bar.java
  @Override public void run() {
    while (!done) {
      show(counter.get());
      before.run();
      preview.run();
      try { Thread.sleep(100); } catch (InterruptedException e) { return; }
    }
  }

  private void show(long n) {
    int cells = 40;
    int filled = (int) Math.min(cells, cells * n / Math.max(1, total));
    StringBuilder sb = new StringBuilder("\r[");
    for (int i = 0; i < cells; i++) sb.append(i < filled ? '#' : ' ');
    sb.append("] ").append(100 * n / Math.max(1, total)).append(" %   ");
    System.out.print(sb);
    System.out.flush();
  }
  • hole 3: the counter the option names; then the sentence: the bar uses …, because …
Shell
java -cp out Render scene.txt --part 2 --counter racy
java -cp out Render scene.txt --part 2 --counter locked
java -cp out Render scene.txt --part 2 --counter atomic
java -cp out Render scene.txt --part 2 --counter perworker
java -cp out Check 2

The check: each repaired counter equals the number of pixels after the join, and during the run its get never decreases and never exceeds the adds begun; the racy counter is reported, not judged. A failure: *locked counted 57 600 but a read during the run went backwards: is get inside the lock?*

Gives: The racy bar short of 100 % under a finished picture, the three repairs at 100 %, and a choice among them by cost, since all three meet the contract. n++ on a shared word is three steps, whatever the word's type (rule 3).

Part 3: Load balancing

The need: Static bands are unequal: the bands with the mirror cube and the sphere are still grey when the sky's bands are done.

Given Tiles.java, which replaces the band loop: the picture cut into tiles; a Dispenser whose int next() must hand out each tile index exactly once, given as a plain next++; and a PerWorkerCounter of tiles per worker, read by get(int worker) and printed at the end. Write: first, as a comment at the hole of next, a prediction of what two workers running next++ at the same time hand out; then, in place of next++, next as one atomic instruction, AtomicInteger.getAndIncrement (a get then a set is still two steps); then each tile counted for its worker; then the sentence: why one atomic instruction suffices, why no lock is needed, and why a count per worker cannot serve as the dispenser.

The dispenser is not a Counter: neither add and get nor a count per worker can hand out a unique index.

Part 1's bands at half the pixels: the sky's three bands done, the others still partly grey
Part 1's bands at half the pixels: the sky's three bands done, the others still partly grey
Javaquest/Tiles.java
  /** Hands out the tile indices 0, 1, 2, ... each exactly once, to any number of threads;
   *  from count on, every call returns count or more: there is no more work. */
  static final class Dispenser {
    private int next = 0;

    // TODO 4: next++ is three steps; predict here what two workers running them at once hand
    // out, then make next() one instruction, and write why one instruction is enough, why no
    // lock is needed, and why a count per worker cannot do it.
    int next() { return next++; }
    
  }

  /** Part 3's render: workers pull tiles from one dispenser until it runs dry. Returns the
   *  line of tiles per worker, the observation of balance. */
  static String render(Scene scene, int threads, Counter counter, Picture picture) throws InterruptedException {
    Tiles tiles = new Tiles(scene.width(), scene.height());
    Dispenser dispenser = new Dispenser();
    PerWorkerCounter tilesDone = new PerWorkerCounter(threads);
    Workers w = new Workers(threads);
    w.start(i -> {
      for (int k = dispenser.next(); k < tiles.count; k = dispenser.next()) {
        tiles.render(scene, k, picture, counter, i);
        // TODO 5: count this tile as worker i's on tilesDone
        
      }
    });
    w.join();
    StringBuilder sb = new StringBuilder("tiles per worker:");
    for (int i = 0; i < threads; i++) sb.append(' ').append(tilesDone.get(i));
    return sb + "  (" + tiles.count + " tiles)";
  }
}
  • hole 4: the prediction, then next as one instruction; then the sentence.
  • hole 5: each tile counted as worker i's on tilesDone.
Shell
java -cp out Render scene.txt --part 3 --counter perworker
java -cp out Check 3

The check: the check wraps the dispenser, calls next() outside any lock so that the race is not hidden, counts how often each index comes out, and requires every count to be one. The tiled picture equals the sequential one, and the tiles per worker add up to the number of tiles; their spread is printed as an observation. A failure: *tile 1 234 was handed out twice: two workers read the same next; what makes getAndIncrement one step?*

Gives: The atomic counter in a second role: handing out work. A lost increment here renders a tile twice instead of skipping one, so the racy dispenser's picture looks right and only the count shows the race. The printed counts show the imbalance the dispenser absorbs; on the laptop of part 0 the tiles took 1.7 s against the bands' 2.1 s on twelve threads, and 3.0 s against 4.6 s on four.

Part 6: The explorer

The need: A new camera position should restart the render at once, without waiting for the old render to finish.

Given Explorer.java, with the keyboard read on the main thread, a render on a fresh Workers per camera, one picture buffer reused across restarts, and restart, which only starts the new render, write three lines: the test of stopped() at the top of the tile loop; stop() on the old workers in restart; join() on the old workers before the new ones start. stop() only sets a flag, which each worker reads at the top of its next tile; join() is what waits for the old workers to end.

As given, a new camera starts a second render beside the first, and the two views mix in one picture. With the stop and without the join, the old workers' last tiles land in the reused buffer among the new view's; the check detects them, the eye rarely does. A plain stop flag shows no failure here: the tile loop calls the tracer and the dispenser, after which this JDK reads the field again. The language does not require it (rule 9); the warm-up's empty loop shows the failure.

Javaquest/Explorer.java
  /** Renders the view on fresh workers, after the render in progress has been stopped and
   *  joined; returns at once, the workers go on. */
  synchronized void restart(Scene view) throws InterruptedException {
    Workers old = current;
    if (old != null) {
      // TODO 7: tell the old render to stop
      
      // TODO 8: and wait until every old worker has ended, before the fresh ones start
      
    }
    Tiles tiles = new Tiles(view.width(), view.height(), ++renders);
    Tiles.Dispenser dispenser = new Tiles.Dispenser();
    Workers fresh = new Workers(threads);
    current = fresh;
    fresh.start(i -> {
      for (int k = dispenser.next(); k < tiles.count; k = dispenser.next()) {
        // TODO 6: ask fresh.stopped() here, at the top of the tile loop, and return if so
        
        tiles.render(view, k, picture, counter, i);
      }
    });
  }
  • hole 6: the test of the flag at the top of the tile loop.
  • hole 7: stop() on the old workers.
  • hole 8: join() on the old workers, before the fresh ones start.
Shell
java -cp out Explorer scene.txt
java -cp out Check 6

The check: a scripted camera change in place of the keyboard: after it, no tile of the old view in the picture, and no old worker writing after the new render has begun. A failure: tile (3, 7) holds the old view: were the old workers joined before the new ones started?

Gives: Cancellation and restart in a fixed order: stop, then join, then a fresh start. The volatile flag gives visibility; the join gives ordering. The result is an interactive ray tracer driven from the terminal.

Part 4: Supersampling and tone mapping (extension)

The need: Jagged edges and hard shadows. Many jittered samples per pixel, with lights of non-zero size, give smooth edges and soft shadows. Lights brighter than 1 require tone mapping, which needs the brightest value of the whole picture before any pixel is converted to eight bits.

Given the design: the render is progressive; the outer loop runs over sample passes, and each pass hands out the tiles anew, so the samples of one pixel come from different workers. A single shared film would be written by every worker; each worker therefore has its own film, Film.java, in fixed point. Each sample's channel is capped at radiance 16, rounded to 1/4 096, and added as an integer of at most 65 536 into one int per channel per pixel. With at most 32 767 samples the sum stays below 2³¹: it cannot overflow, and the order of addition does not change it. Also given: ToneMap.java, which maps each band of the merged film by its own maximum, with no fold, which is wrong; and Rng.of(x, y, s), the generator of sample s of pixel (x, y).

Write: the merge of the per-worker films into one, starting from its identity; the fold of the maximum luminance over the bands of the merged film, with its combine and identity, followed by one mapping of the whole film; and, in the samples loop, the generator Rng.of(x, y, s) in place of the worker's.

The preview is the merged films, tone-mapped, rewritten during the render: the noise of the soft shadows clears pass by pass. The sixteen passes of scene.txt took about 28 s on the laptop of part 0.

Hard shadows at one sample per pixel (part 0), soft shadows at sixteen (part 4), darker by the tone map
Hard shadows at one sample per pixel (part 0), soft shadows at sixteen (part 4), darker by the tone map
Javaquest/Film.java
  /** The merge of the workers' films: one film holding every sample of every film. */
  static Film merge(Film[] films) {
    // TODO 9: every film, added from the zero film; until then, the first worker's film alone
    return films[0];
    
  }
Javaquest/Film.java
  /** Passes over the tiles, each pass handing the tiles out anew, each worker adding its
   *  samples to its own film; the films after the join. */
  static Film[] films(Scene scene, int threads, Counter counter, Picture picture, Bar bar) throws InterruptedException {
    int samples = Math.min(scene.samples(), MAX_SAMPLES);
    Tiles tiles = new Tiles(scene.width(), scene.height());
    Tiles.Dispenser[] passes = new Tiles.Dispenser[samples];
    for (int s = 0; s < samples; s++) passes[s] = new Tiles.Dispenser();
    Film[] films = new Film[threads];
    for (int i = 0; i < threads; i++) films[i] = new Film(scene.width(), scene.height());
    if (bar != null) bar.beforePreview(() -> ToneMap.map(merge(films), picture));   // the picture so far, from the films as they are
    Workers w = new Workers(threads);
    w.start(i -> {
      Film mine = films[i];
      for (int s = 0; s < samples; s++)
        for (int k = passes[s].next(); k < tiles.count; k = passes[s].next())
          for (int y = tiles.y0(k); y < tiles.y1(k); y++)
            for (int x = tiles.x0(k); x < tiles.x1(k); x++) {
              // TODO 11: the generator of this sample is the pixel's and the sample's, Rng.of(x, y, s),
              // not the worker's: then the picture is a function of the scene alone
              mine.add(x, y, Tracer.sample(scene, x, y, Rng.of(i, 0, s)));
              
              counter.add(i);
            }
    });
    w.join();
    return films;
  }
}
Javaquest/ToneMap.java
  /** The whole film into the picture: the fold of the maximum over the bands, then the mapping. */
  static void map(Film film, Picture picture) {
    int h = film.height;
    // TODO 10: each band is mapped by its own maximum, and no band knows the others': fold
    // the maximum over all the bands first, with its combine and its identity, then map every
    // band by the one value.
    for (int band = 0; band < BANDS; band++) {
      int y0 = h * band / BANDS, y1 = h * (band + 1) / BANDS;
      mapRows(film, picture, y0, y1, maxLuminance(film, y0, y1));
    }
    
  }
}
  • hole 9: the merge, every film added to the zero film.
  • hole 10: the fold of the maximum over all bands, then one mapping.
  • hole 11: the sample's generator, from the pixel and the sample.
Shell
java -cp out Render scene.txt --part 4 --counter perworker
java -cp out Check 4

The check: the merged film equals the sequential many-sample film exactly, on a reference rendered once at a reduced size: first the sample counts per pixel (the merge and its identity), then the values (the seeding); then the tone map scales the whole picture by one maximum; then the picture on one worker equals the picture on twelve. Failures: pixel (0, 0) holds 2 samples of 6: is the merge adding every film, from the zero film?; band 7 is brighter than it should be: is the maximum folded over all bands before any pixel is mapped?

Gives: A fold with its two laws, combine and identity, and the visible cost of its absence: bands of different brightness. The per-worker film is a design choice, not a repair: a racy shared film would lose a few samples in a hundred thousand, invisibly. Seeding by pixel and sample makes the picture a function of the scene alone, whichever worker renders which tile in which pass.

Part 5: The video (extension)

The need: A cube turns, and its reflection in the mirror cube must turn with it.

Given Video.java, at one sample per pixel and half the picture's width and height, with its design described at the top of the file. The workers live for the whole video. A frame is one buffer whose pixels are owned by tiles, as in part 3. The scene of a frame is an immutable value, Scene.at(k), held in a field that every worker reads and only the barrier's action writes; the same holds for the current frame and the dispenser. For frame k, each worker renders its tiles and arrives at the barrier. The action, run by the last arrival before any party is released, puts the finished frame into the buffer and installs frame k + 1, or the end marker after the last frame. The main thread is the encoder: it takes frames until the end marker, writes each, then joins the workers.

Two happens-before chains carry a frame: the barrier from every worker to the last arrival, and the buffer from the last arrival to the encoder, which is not a party of the barrier. The action's put may block on a full buffer while the other parties wait at the barrier; this is harmless.

As given, there is no barrier: each worker that finishes frame k advances the scene and starts frame k + 1 on its own, and a frame is sent when a plain count says all workers are done. Write: the barrier at the end of each worker's frame, with nextFrame as its action; Frame.END into the buffer after the last frame, and the encoder's loop taking frames until it; and, in place of code, the answer to this question: why do the frames reach the encoder in order, and in which design would the encoder have to hold frames back by number?

The 60 frames of scene.txt took about 30 s on the laptop of part 0.

Frame 10 of the video, at 1280 × 720: the blue cube turned by 30 degrees from frame 0
Frame 10 of the video, at 1280 × 720: the blue cube turned by 30 degrees from frame 0
Javaquest/Video.java
  /** The barrier's action: the finished frame to the encoder, then the next frame installed. */
  void nextFrame() throws InterruptedException {
    Frame done = frame;
    buffer.put(done);                            // the hand-over: the buffer publishes the frame to the encoder
    advance(done.k + 1);
    // TODO 13 (a): after the last frame, the end marker goes into the buffer too
    
  }

  /** One worker: its tiles of each frame, then the barrier; until the end marker. */
  void worker(int i) {
    try {
      while (true) {
        Frame f = frame;                         // this frame and its dispenser, installed by the action
        if (f == Frame.END) return;
        Tiles.Dispenser d = dispenser;
        for (int k = d.next(); k < tiles.count; k = d.next())
          tiles.render(scene, k, f.picture, counter, i);   // the scene field: the one the action installed
        // TODO 12: no barrier: whoever finishes its tiles moves the scene on and begins the
        // next frame at once, while the others may still be on this one; and the frame goes to
        // the encoder when a plain count says everyone has finished. Replace the two lines by
        // the barrier's await, whose action is nextFrame.
        if (f == frame) advance(f.k + 1);
        if (++finished == threads) { finished = 0; buffer.put(f); if (frame == Frame.END) buffer.put(Frame.END); }
        
      }
    } catch (Exception e) {
      // the barrier is broken (BrokenBarrierException) or this worker was interrupted: it ends
    }
  }

  /** Renders the video: the workers over the frames, the encoder taking them in order. */
  void run(Sink sink) throws Exception {
    Workers w = new Workers(threads);
    w.start(this::worker);
    // TODO 13 (b): the encoder's loop: take frames and give each to the sink, until the end marker
    todo(13);
    
    w.join();
  }
  • hole 12: barrier.await() at the end of each worker's frame.
  • hole 13: the end marker after the last frame, and the encoder's loop until it.
  • the question: why in order, and when frames must be held back by number.
Shell
java -cp out Video scene.txt
ffmpeg -framerate 24 -i frames/frame-%04d.png -pix_fmt yuv420p video.mp4
java -cp out Check 5

The check: the frames arrive in order and each equals its sequential frame; a run that does not end is reported at a deadline. A failure: frame 17 holds tiles from two scenes: what moved the scene before every worker had finished the frame?

Gives: The barrier in its place, and without it a frame torn between two rotations: a fast worker starts frame k + 1 on the advanced scene while a slow one still renders frame k. State shared between phases (scene, frame, dispenser) is changed by one thread inside the barrier. The buffer with its waits in loops and notifyAll (rules 4 and 5), and the hang when the end marker is missing. Ordering of results as a separate concern: settled here by the phases, elsewhere by a sequence number.

The last question and the mini-project

For every piece of shared state in the program, the preview's read included, say which technique protects it: ownership, a lock or an atomic word, or a copy per thread. For every hand-over between threads or phases, say which mechanism orders it: a join, a barrier, a monitor's wait or a volatile flag, and why that one. The sentence holes of the parts answer it piece by piece.

The mini-project rebuilds BoundedBuffer as a queue, three ways: first the warm-up's class as the one-lock queue, with its point of effect named; then a two-lock queue with a dummy node; then a lock-free queue with a lagging tail.

Questions on paper

Ten questions on the two primitives of the lecture that are not classes, the join and the visible write, for the week after the lab: primitives.pdf. They are not part of the warm-up. The lab collects nothing.