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

חזרה למפגשBack
JavaJava

Locks, Atomic ו-ConcurrentHashMapLocks, Atomic & ConcurrentHashMap

מפגש 36: ReentrantLock ו-ReadWriteLock, AtomicInteger ו-compareAndSet, ו-ConcurrentHashMap.Session 36: ReentrantLock and ReadWriteLock, AtomicInteger and compareAndSet, and ConcurrentHashMap.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • AtomicIntegerAtomicInteger
  • ReentrantLock עם try/finallyReentrantLock with try/finally
  • ConcurrentHashMap ו-mergeConcurrentHashMap and merge
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

המונחים של המפגש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.
נושאTopic 2

AtomicIntegerAtomicInteger

AtomicIntegerAtomicInteger

  • בלי 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.
נושא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.
נושאTopic 5

פרויקט מדףShelf project

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

  • מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache

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.

בלי 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

למה 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

כדי שהמנעול ישתחרר גם אם נזרקה חריגהSo the lock is released even if an exception was thrown

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

לא: זה get ואז put, ומישהו יכול להיכנס באמצעNo: it's a get then a put, and someone can slip in between

מה מחזיר compareAndSet(5, 6) כשהערך הנוכחי 7?What does compareAndSet(5, 6) return when the current value is 7?

  • false, והערך נשאר 7false, and the value stays 7
  • true, והערך 6true, and the value is 6
  • חריגהAn exception
  • מחכהIt waits

false, והערך נשאר 7false, and the value stays 7

מונה ביקורים אטומיAn atomic visit counter

  • static final AtomicInteger hits.static final AtomicInteger hits.

מלאי עם ReentrantLockStock with a ReentrantLock

  • מלאי 5000.A stock of 5000.

צייד באגים: 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.

שיא עם compareAndSetA record with compareAndSet

  • שלושה threads מציעים ציונים.Three threads offer scores.

מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache

  • BookCache.details(title) משתמשת ב-computeIfAbsent של ConcurrentHashMap:BookCache.details(title) uses ConcurrentHashMap's computeIfAbsent:

ReadWriteLockReadWriteLock

  • Catalog עם ReentrantReadWriteLock:Catalog with a ReentrantReadWriteLock:

tryLock עם זמן קצובtryLock with a timeout

  • main מחזיק את מנעול המדפסת.main holds the printer lock.

אין צורך ב-synchronized.No synchronized needed.

Lock lock = new ReentrantLock();Lock lock = new ReentrantLock();

loans.merge(key, 1, Integer::sum);loans.merge(key, 1, Integer::sum);

קוראים cur, אם הציון לא גבוה יותר יוצאים, אחרת מנסים compareAndSet(cur, score) עד שמצליחים.Read cur, leave if the score isn't higher, otherwise try compareAndSet(cur, score) until it works.

computeIfAbsent מריץ את הפונקציה פעם אחת לכל מפתח, באופן אטומי.computeIfAbsent runs the function once per key, atomically.

מה למדנו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

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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