נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • Atomic: AtomicInteger, AtomicLong ודומיהם:Atomic: AtomicInteger, AtomicLong and friends:
  • compareAndSet: x.compareAndSet(expected, next):compareAndSet: x.compareAndSet(expected, next):
  • בלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.
  • lock() ואז try, ו-unlock() תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.lock() then try, and unlock() always in finally: even if the code inside throws, the lock is released.
  • ארבעה threads סופרים מילים לאותה מפה.Four threads count words into the same map.
  • merge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.merge is atomic, so the count is always right: each word times 4.
  • מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache

מונחיםTerms

  • AtomicAtomic: AtomicInteger, AtomicLong ודומיהם: incrementAndGet() ו-addAndGet() הם צעד אחד שאי אפשר לחתוך, בלי מנעול.AtomicInteger, AtomicLong and friends: incrementAndGet() and addAndGet() are one step nobody can cut into, with no lock.
  • compareAndSetcompareAndSet: x.compareAndSet(expected, next): משנה רק אם הערך עדיין expected, ומחזיר אם הצליח. בלולאה: קוראים, מחשבים, ומנסים שוב אם מישהו הקדים.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.
  • ReentrantLockReentrantLock: מנעול מפורש: lock(), ואז try { ... } finally { unlock(); }. מאפשר tryLock (גם עם זמן קצוב) ו-lockInterruptibly.An explicit lock: lock(), then try { ... } finally { unlock(); }. It allows tryLock (with a timeout too) and lockInterruptibly.
  • ReadWriteLockReadWriteLock: שני מנעולים: כמה קוראים יחד, או כותב אחד לבד. טוב כשיש הרבה קריאות ומעט כתיבות.Two locks: several readers together, or one writer alone. Good when there are many reads and few writes.
  • ConcurrentHashMapConcurrentHashMap: Map בטוח ל-threads בלי לנעול את כולו. merge, compute ו-computeIfAbsent אטומיים; get ואז put לא.A thread-safe Map that doesn't lock all of itself. merge, compute and computeIfAbsent are atomic; get then put isn't.
  • AtomicAtomic: AtomicInteger, AtomicLong ודומיהם: incrementAndGet() ו-addAndGet() הם צעד אחד שאי אפשר לחתוך, בלי מנעול.AtomicInteger, AtomicLong and friends: incrementAndGet() and addAndGet() are one step nobody can cut into, with no lock.
  • compareAndSetcompareAndSet: x.compareAndSet(expected, next): משנה רק אם הערך עדיין expected, ומחזיר אם הצליח. בלולאה: קוראים, מחשבים, ומנסים שוב אם מישהו הקדים.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.
  • ReentrantLockReentrantLock: מנעול מפורש: lock(), ואז try { ... } finally { unlock(); }. מאפשר tryLock (גם עם זמן קצוב) ו-lockInterruptibly.An explicit lock: lock(), then try { ... } finally { unlock(); }. It allows tryLock (with a timeout too) and lockInterruptibly.
  • ReadWriteLockReadWriteLock: שני מנעולים: כמה קוראים יחד, או כותב אחד לבד. טוב כשיש הרבה קריאות ומעט כתיבות.Two locks: several readers together, or one writer alone. Good when there are many reads and few writes.
  • ConcurrentHashMapConcurrentHashMap: Map בטוח ל-threads בלי לנעול את כולו. merge, compute ו-computeIfAbsent אטומיים; get ואז put לא.A thread-safe Map that doesn't lock all of itself. merge, compute and computeIfAbsent are atomic; get then put isn't.

Cheatsheet

AtomicIntegerAtomicInteger
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();
}
ReentrantLock עם try/finallyReentrantLock with try/finally
Runnable job = () -> {
    for (int i = 0; i < 50000; i++) {
        lock.lock();
        try {
            total++;
        } finally {
            lock.unlock();
        }
    }
};
ConcurrentHashMap ו-mergeConcurrentHashMap and merge
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();
}

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do

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