×

java · level 3 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An reads, adds and writes in one step.

Locks work, but they are heavy for one number. AtomicInteger, from java.util.concurrent.atomic, holds an int and changes it atomically: as one step that no other thread can interrupt or see half done.

incrementAndGet() adds one and hands back the new value. addAndGet(5) adds any amount. get() reads it. There is no lock to forget, because the safety is built into each method.

It is an object, not a plain int, so ++ and + do not work on it. Every change goes through a method. That is the price of safety, and it makes every change stand out.

import java.util.concurrent.atomic.AtomicInteger;
public class Main {
    static void scan(AtomicInteger parcels, int count) {
        for (int i = 0; i < count; i++) {
            parcels.incrementAndGet();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger parcels = new AtomicInteger();
        Thread belt1 = new Thread(() -> scan(parcels, 30000));
        Thread belt2 = new Thread(() -> scan(parcels, 45000));
        belt1.start();
        belt2.start();
        belt1.join();
        belt2.join();
        System.out.println("Parcels scanned: " + parcels.get());
        System.out.println("After one more: " + parcels.addAndGet(1));
    }
}

new AtomicInteger() starts at 0; pass a number, like new AtomicInteger(10), to start somewhere else.