נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
Locks, Atomic ו-ConcurrentHashMapLocks, Atomic & ConcurrentHashMap
מפגש 36: ReentrantLock ו-ReadWriteLock, AtomicInteger ו-compareAndSet, ו-ConcurrentHashMap.Session 36: ReentrantLock and ReadWriteLock, AtomicInteger and compareAndSet, and ConcurrentHashMap.
ReentrantLock ו-ReadWriteLock, AtomicInteger ו-compareAndSet, ו-ConcurrentHashMap. בסוף המפגש מוסיפים צעד לפרויקט המלווה.ReentrantLock and ReadWriteLock, AtomicInteger and compareAndSet, and ConcurrentHashMap. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- AtomicIntegerAtomicInteger
- ReentrantLock עם try/finallyReentrantLock with try/finally
- ConcurrentHashMap ו-mergeConcurrentHashMap and merge
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- Atomic:
AtomicInteger, AtomicLong ודומיהם:Atomic: AtomicInteger, AtomicLong and friends: - compareAndSet:
x.compareAndSet(expected, next):compareAndSet: x.compareAndSet(expected, next): - ReentrantLock: מנעול מפורש:ReentrantLock: An explicit lock:
- ReadWriteLock: שני מנעולים:ReadWriteLock: Two locks:
- ConcurrentHashMap: Map בטוח ל-threads בלי לנעול את כולו.ConcurrentHashMap: A thread-safe Map that doesn't lock all of itself.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
AtomicIntegerAtomicInteger
AtomicIntegerAtomicInteger
- בלי
synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.
בלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.נושאTopic 3
ReentrantLock עם try/finallyReentrantLock with try/finally
ReentrantLock עם 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.
lock() ואז try, ו-unlock() תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.lock() then try, and unlock() always in finally: even if the code inside throws, the lock is released.נושאTopic 4
ConcurrentHashMap ו-mergeConcurrentHashMap and merge
ConcurrentHashMap ו-mergeConcurrentHashMap and merge
- ארבעה threads סופרים מילים לאותה מפה.Four threads count words into the same map.
merge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.merge is atomic, so the count is always right: each word times 4.
ארבעה threads סופרים מילים לאותה מפה. merge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.Four threads count words into the same map. merge is atomic, so the count is always right: each word times 4.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache
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.Atomic: AtomicInteger, AtomicLong ודומיהם:Atomic: AtomicInteger, AtomicLong and friends:
המונחים של המפגשThis session's termscompareAndSet: x.compareAndSet(expected, next):compareAndSet: x.compareAndSet(expected, next):
המונחים של המפגשThis session's termsReentrantLock: מנעול מפורש:ReentrantLock: An explicit lock:
המונחים של המפגשThis session's termsReadWriteLock: שני מנעולים:ReadWriteLock: Two locks:
המונחים של המפגשThis session's termsConcurrentHashMap: Map בטוח ל-threads בלי לנעול את כולו.ConcurrentHashMap: A thread-safe Map that doesn't lock all of itself.
המונחים של המפגשThis session's termsבלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.
AtomicIntegerAtomicIntegerlock() ואז try, ו-unlock() תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.lock() then try, and unlock() always in finally: even if the code inside throws, the lock is released.
ReentrantLock עם try/finallyReentrantLock with try/finallyארבעה threads סופרים מילים לאותה מפה.Four threads count words into the same map.
ConcurrentHashMap ו-mergeConcurrentHashMap and mergemerge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.merge is atomic, so the count is always right: each word times 4.
ConcurrentHashMap ו-mergeConcurrentHashMap and mergeמדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה unlock() ב-finally?Why unlock() in finally?
- כדי שהמנעול ישתחרר גם אם נזרקה חריגהSo the lock is released even if an exception was thrown
- כי Java מחייבתBecause Java requires it
- זה מהיר יותרIt's faster
- לא צריךIt's not needed
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כדי שהמנעול ישתחרר גם אם נזרקה חריגהSo the lock is released even if an exception was thrown
נכון, אחרת כולם יחכו לנצח.Right, otherwise everyone waits forever.map.put(k, map.get(k) + 1) על ConcurrentHashMap משני threads. בטוח?map.put(k, map.get(k) + 1) on a ConcurrentHashMap from two threads. Safe?
- לא: זה get ואז put, ומישהו יכול להיכנס באמצעNo: it's a get then a put, and someone can slip in between
- כן, המפה בטוחהYes, the map is safe
- רק עם volatileOnly with volatile
- זורק חריגהIt throws
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.לא: זה get ואז put, ומישהו יכול להיכנס באמצעNo: it's a get then a put, and someone can slip in between
נכון. משתמשים ב-merge.Right. Use merge.מה מחזיר compareAndSet(5, 6) כשהערך הנוכחי 7?What does compareAndSet(5, 6) return when the current value is 7?
false, והערך נשאר 7false, and the value stays 7true, והערך 6true, and the value is 6- חריגהAn exception
- מחכהIt waits
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.false, והערך נשאר 7false, and the value stays 7
נכון.Right.מונה ביקורים אטומיAn atomic visit counter
static final AtomicInteger hits.static final AtomicInteger hits.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מלאי עם ReentrantLockStock with a ReentrantLock
- מלאי 5000.A stock of 5000.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: get ואז putBug hunter: get then put
- המפה היא
ConcurrentHashMap, ובכל זאת הספירה יוצאת נמוכה מדי, ולא תמיד אותו דבר.The map is a ConcurrentHashMap, and still the count comes out too low, and not always the same.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.שיא עם compareAndSetA record with compareAndSet
- שלושה threads מציעים ציונים.Three threads offer scores.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache
BookCache.details(title) משתמשת ב-computeIfAbsent של ConcurrentHashMap:BookCache.details(title) uses ConcurrentHashMap's computeIfAbsent:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.ReadWriteLockReadWriteLock
Catalog עם ReentrantReadWriteLock:Catalog with a ReentrantReadWriteLock:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.tryLock עם זמן קצובtryLock with a timeout
- main מחזיק את מנעול המדפסת.main holds the printer lock.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.אין צורך ב-synchronized.No synchronized needed.
מונה ביקורים אטומיAn atomic visit counterLock lock = new ReentrantLock();Lock lock = new ReentrantLock();
מלאי עם ReentrantLockStock with a ReentrantLockloans.merge(key, 1, Integer::sum);loans.merge(key, 1, Integer::sum);
צייד באגים: get ואז putBug hunter: get then putקוראים cur, אם הציון לא גבוה יותר יוצאים, אחרת מנסים compareAndSet(cur, score) עד שמצליחים.Read cur, leave if the score isn't higher, otherwise try compareAndSet(cur, score) until it works.
שיא עם compareAndSetA record with compareAndSetcomputeIfAbsent מריץ את הפונקציה פעם אחת לכל מפתח, באופן אטומי.computeIfAbsent runs the function once per key, atomically.
מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cacheמה למדנוWhat we learned
- Atomic:
AtomicInteger, AtomicLong ודומיהם:Atomic: AtomicInteger, AtomicLong and friends: - בלי
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.
- מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.