java · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Before or after? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger ticket = new AtomicInteger(10);
int a = ticket.getAndIncrement();
int b = ticket.incrementAndGet();
System.out.println(a + " " + b + " " + ticket.get());
}
}
your turn
Your turn. Total the donations.
On line 5, add each donation to the total in one atomic step.
output
press run to see what happens
fix it
The play counter will not compile. Can you fix it?
output
press run to see what happens
- Java says
++cannot work on anAtomicInteger. Look at line 5. - An
AtomicIntegeris an object, so every change goes through one of its methods. - Change line 5 to
plays.incrementAndGet();, then run.
nailed it
you can count across threads without locks. :D
- Atomic means one step that no thread can break into.
incrementAndGetandaddAndGetchange the value safely.++does not work on anAtomicInteger; call a method.
new words in your collection
- atomic
- AtomicInteger
This lesson isn’t saved. A free account remembers every lesson you finish.