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,AtomicLongand friends:incrementAndGet()andaddAndGet()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 stillexpected, 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(), thentry { ... } finally { unlock(); }. It allowstryLock(with a timeout too) andlockInterruptibly. - 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,computeandcomputeIfAbsentare atomic;getthenputisn't.
02AtomicIntegerAtomicInteger
בלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.
No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.
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());
}
}200000
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
200000 | 5 |
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.
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);
}
}100000
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
100000 | 5 |
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.
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));
}
}{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.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.