חלק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.
הנקודות החשובותKey points
- Atomic:
AtomicInteger,AtomicLongודומיהם:Atomic:AtomicInteger,AtomicLongand friends: - compareAndSet:
x.compareAndSet(expected, next):compareAndSet:x.compareAndSet(expected, next): - בלי
synchronizedובלי מנעול, ובכל זאת תמיד 200,000:incrementAndGetאטומי.Nosynchronizedand no lock, and still always 200,000:incrementAndGetis Atomic. lock()ואזtry, ו-unlock()תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.lock()thentry, andunlock()always infinally: even if the code inside throws, the lock is released.- ארבעה threads סופרים מילים לאותה מפה.Four threads count words into the same map.
mergeאטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.mergeis 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,AtomicLongand friends:incrementAndGet()andaddAndGet()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 stillexpected, 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(), thentry { ... } finally { unlock(); }. It allowstryLock(with a timeout too) andlockInterruptibly. - 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,computeandcomputeIfAbsentare atomic;getthenputisn't. - AtomicAtomic:
AtomicInteger,AtomicLongודומיהם:incrementAndGet()ו-addAndGet()הם צעד אחד שאי אפשר לחתוך, בלי מנעול.AtomicInteger,AtomicLongand friends:incrementAndGet()andaddAndGet()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 stillexpected, 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(), thentry { ... } finally { unlock(); }. It allowstryLock(with a timeout too) andlockInterruptibly. - 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,computeandcomputeIfAbsentare atomic;getthenputisn'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 |
|---|