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

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

Locks, Atomic ו-ConcurrentHashMapLocks, Atomic & ConcurrentHashMap

ReentrantLock ו-ReadWriteLock, AtomicInteger ו-compareAndSet, ו-ConcurrentHashMap.

ReentrantLock and ReadWriteLock, AtomicInteger and compareAndSet, and ConcurrentHashMap.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • Atomic: AtomicInteger, AtomicLong ודומיהם: incrementAndGet() ו-addAndGet() הם צעד אחד שאי אפשר לחתוך, בלי מנעול.Atomic: AtomicInteger, AtomicLong and friends: incrementAndGet() and addAndGet() are one step nobody can cut into, with no lock.
  • compareAndSet: x.compareAndSet(expected, next): משנה רק אם הערך עדיין expected, ומחזיר אם הצליח. בלולאה: קוראים, מחשבים, ומנסים שוב אם מישהו הקדים.compareAndSet: x.compareAndSet(expected, next): changes only if the value is still expected, and returns whether it worked. In a loop: read, compute, and retry if someone got there first.
  • ReentrantLock: מנעול מפורש: lock(), ואז try { ... } finally { unlock(); }. מאפשר tryLock (גם עם זמן קצוב) ו-lockInterruptibly.ReentrantLock: An explicit lock: lock(), then try { ... } finally { unlock(); }. It allows tryLock (with a timeout too) and lockInterruptibly.
  • ReadWriteLock: שני מנעולים: כמה קוראים יחד, או כותב אחד לבד. טוב כשיש הרבה קריאות ומעט כתיבות.ReadWriteLock: Two locks: several readers together, or one writer alone. Good when there are many reads and few writes.
  • ConcurrentHashMap: Map בטוח ל-threads בלי לנעול את כולו. merge, compute ו-computeIfAbsent אטומיים; get ואז put לא.ConcurrentHashMap: A thread-safe Map that doesn't lock all of itself. merge, compute and computeIfAbsent are atomic; get then put isn't.

02AtomicIntegerAtomicInteger

בלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.

No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.

Main.java
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            for (int i = 0; i < 100000; i++) {
                count.incrementAndGet();
            }
        };
        Thread[] ts = new Thread[2];
        for (int k = 0; k < ts.length; k++) {
            ts[k] = new Thread(job);
            ts[k].start();
        }
        for (Thread t : ts) {
            t.join();
        }
        System.out.println(count.get());
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
200000

5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
2000005
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet

03ReentrantLock עם try/finallyReentrantLock with try/finally

lock() ואז try, ו-unlock() תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.

lock() then try, and unlock() always in finally: even if the code inside throws, the lock is released.

Main.java
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static final ReentrantLock lock = new ReentrantLock();
    static int total = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            for (int i = 0; i < 50000; i++) {
                lock.lock();
                try {
                    total++;
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread[] ts = new Thread[2];
        for (int k = 0; k < ts.length; k++) {
            ts[k] = new Thread(job);
            ts[k].start();
        }
        for (Thread t : ts) {
            t.join();
        }
        System.out.println(total);
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
100000

5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
1000005
count++ בתוך synchronizedcount++ inside synchronized

04ConcurrentHashMap ו-mergeConcurrentHashMap and merge

ארבעה threads סופרים מילים לאותה מפה. merge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.

Four threads count words into the same map. merge is atomic, so the count is always right: each word times 4.

Main.java
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    static final Map<String, Integer> counts = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            for (String w : "to be or not to be".split(" ")) {
                counts.merge(w, 1, Integer::sum);
            }
        };
        Thread[] ts = new Thread[4];
        for (int k = 0; k < ts.length; k++) {
            ts[k] = new Thread(job);
            ts[k].start();
        }
        for (Thread t : ts) {
            t.join();
        }
        System.out.println(new TreeMap<>(counts));
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
{be=8, not=4, or=4, to=8}

5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
{be=8, not=4, or=4, to=8}5
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet

05הצעד של היום בפרויקט מדףToday's step in the Shelf project

BookCache.details(title) משתמשת ב-computeIfAbsent של ConcurrentHashMap: הטעינה (שמגדילה loads) רצה פעם אחת לכל כותר, גם כששני threads מבקשים יחד. הדפיסו Dune (4 letters) | loaded 3 times.

BookCache.details(title) uses ConcurrentHashMap's computeIfAbsent: the load (which bumps loads) runs once per title, even when two threads ask together. Print Dune (4 letters) | loaded 3 times.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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