נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
33
חלקPart 6: Concurrency ו-ThreadsConcurrency & threads כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

volatile ו-Java Memory Modelvolatile & the Java Memory Model

נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק.

Visibility, happens-before, volatile, and when it isn't enough.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

עצירה של ייבואStopping an import

תזכורת: מה ביקשוReminder: the task

thread ייבוא עובד באצוות (כל אצווה sleep(5)) כל עוד running (volatile). main מחכה 40ms, מכבה את הדגל ומחכה עם join. הדפיסו importer stopped: true ואז done.

An import thread works in batches (each sleep(5)) while running (volatile). main waits 40ms, turns the flag off and waits with join. Print importer stopped: true then done.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread importer = new Thread(() -> {
            int batches = 0;
            while (running) {
                batches++;
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    return;
                }
            }
            System.out.println("importer stopped: " + (batches > 0));
        });
        importer.start();
        Thread.sleep(40);
        running = false;
        importer.join();
        System.out.println("done");
    }
}
פלטOutput
importer stopped: true
done

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

פרסום הגדרותPublishing settings

תזכורת: מה ביקשוReminder: the task

static volatile Config config = null. ה-reader מחכה (Thread.onSpinWait()) עד שהשדה לא null ומדפיס theme=dark size=14. main יוצר new Config("dark", 14) ומפרסם.

static volatile Config config = null. The reader waits (Thread.onSpinWait()) until the field isn't null and prints theme=dark size=14. main creates new Config("dark", 14) and publishes it.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static volatile Config config = null;

    public static void main(String[] args) throws InterruptedException {
        Thread reader = new Thread(() -> {
            while (config == null) {
                Thread.onSpinWait();
            }
            System.out.println("theme=" + config.theme() + " size=" + config.size());
        });
        reader.start();
        config = new Config("dark", 14);
        reader.join();
    }
}

record Config(String theme, int size) {
}
פלטOutput
theme=dark size=14

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

צייד באגים: volatile לא מספיקBug hunter: volatile isn't enough

תזכורת: מה ביקשוReminder: the task

התוכנית מהתזכורת מאבדת עדכונים למרות volatile. תקנו עם מתודה static synchronized void inc() כך שתמיד יודפס 200000.

The program from the refresher loses updates despite volatile. Fix it with a static synchronized void inc() method so it always prints 200000.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

count++ בלי הגנה: נסו לאבד עדכוןcount++ unprotected: try to lose an update
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int count = 0;

    static synchronized void inc() {
        count++;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            for (int i = 0; i < 100000; i++) {
                inc();
            }
        };
        Thread a = new Thread(job);
        Thread b = new Thread(job);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(count);
    }
}
פלטOutput
200000

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

join כגבולjoin as a boundary

תזכורת: מה ביקשוReminder: the task

thread ממלא מערך בריבועים 0–9. אחרי join, main סוכם (בלי volatile ובלי synchronized) ומדפיס 285. למה זה בטוח? בגלל happens-before של join.

A thread fills an array with the squares 0–9. After join, main sums it (no volatile, no synchronized) and prints 285. Why is it safe? Because of join's happens-before.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        int[] squares = new int[10];
        Thread filler = new Thread(() -> {
            for (int i = 0; i < squares.length; i++) {
                squares[i] = i * i;
            }
        });
        filler.start();
        filler.join();
        int sum = 0;
        for (int s : squares) {
            sum += s;
        }
        System.out.println(sum);
    }
}
פלטOutput
285

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import

תזכורת: מה ביקשוReminder: the task

Importer מייבא 1000 שורות (2ms לשורה) ובודק לפני כל שורה את cancelled (volatile). main מבטל אחרי 30ms. הדפיסו cancelled: true ואז stopped early: true.

Importer imports 1000 lines (2ms per line) and checks cancelled (volatile) before each line. main cancels after 30ms. Print cancelled: true then stopped early: true.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        List<String> lines = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            lines.add("Book " + i);
        }
        Importer imp = new Importer(lines);
        Thread t = new Thread(imp);
        t.start();
        Thread.sleep(30);
        imp.cancel();
        t.join();
        System.out.println("cancelled: " + imp.isCancelled());
        System.out.println("stopped early: " + (imp.imported() < lines.size()));
    }
}

class Importer implements Runnable {
    private final List<String> lines;
    private volatile boolean cancelled = false;
    private volatile int imported = 0;

    Importer(List<String> lines) {
        this.lines = lines;
    }

    void cancel() {
        cancelled = true;
    }

    boolean isCancelled() {
        return cancelled;
    }

    int imported() {
        return imported;
    }

    @Override
    public void run() {
        for (String line : lines) {
            if (cancelled) {
                return;
            }
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                return;
            }
            imported++;
        }
    }
}
פלטOutput
cancelled: true
stopped early: true

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

Double-checked lockingDouble-checked locking

תזכורת: מה ביקשוReminder: the task

Registry.get() יוצר מופע יחיד בעצלות: בודק בלי נעילה, ורק אם null נועל ובודק שוב. השדה חייב להיות volatile, אחרת thread אחר עלול לראות עצם שנבנה חלקית. הדפיסו same instance: true, created 1.

Registry.get() creates a single instance lazily: it checks without locking, and only if null locks and checks again. The field must be volatile, or another thread might see a half-built object. Print same instance: true, created 1.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Registry[] seen = new Registry[2];
        Thread a = new Thread(() -> seen[0] = Registry.get());
        Thread b = new Thread(() -> seen[1] = Registry.get());
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("same instance: " + (seen[0] == seen[1]) + ", created " + Registry.created);
    }
}

class Registry {
    private static volatile Registry instance;
    static int created = 0;

    private Registry() {
        created++;
    }

    static Registry get() {
        Registry r = instance;
        if (r == null) {
            synchronized (Registry.class) {
                r = instance;
                if (r == null) {
                    r = new Registry();
                    instance = r;
                }
            }
        }
        return r;
    }
}
פלטOutput
same instance: true, created 1

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

volatile נושא איתו עודvolatile carries more along

תזכורת: מה ביקשוReminder: the task

כתבו את התוכנית מהתזכורת: data רגיל, ready volatile. main כותב data = 42 ואז ready = true. ה-reader מחכה ל-ready ומדפיס data=42. הסבירו לעצמכם למה זה מובטח.

Write the program from the refresher: a plain data, a volatile ready. main writes data = 42 then ready = true. The reader waits for ready and prints data=42. Explain to yourself why that's guaranteed.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int data = 0;
    static volatile boolean ready = false;

    public static void main(String[] args) throws InterruptedException {
        Thread reader = new Thread(() -> {
            while (!ready) {
                Thread.onSpinWait();
            }
            System.out.println("data=" + data);
        });
        reader.start();
        data = 42;
        ready = true;
        reader.join();
    }
}
פלטOutput
data=42

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich