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

JavaJava
38
חלקPart 6: Concurrency ו-ThreadsConcurrency & threads כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Deadlock, livelock ו-starvationDeadlock, livelock & starvation

איך threads נתקעים, איך מאבחנים עם jstack ו-thread dump, ואיך מונעים: סדר מנעולים, tryLock וזמנים קצובים.

How threads get stuck, how to diagnose with jstack and a thread dump, and how to prevent it: lock ordering, tryLock and timeouts.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה צריך כדי שיהיה deadlock?What's needed for a deadlock?

2. הדרך הפשוטה ביותר למנוע deadlock בין שני מנעולים?The simplest way to prevent a deadlock between two locks?

3. התוכנית קפאה בלי שגיאה. מה הכלי הראשון?The program froze with no error. The first tool?

תרגיליםExercises

תרגילExercise 1

שני מדפים, סדר אחדTwo shelves, one order

move(who) נועלת את shelfA ואז את shelfB. שני threads קוראים לה. הסדר בין T1 ל-T2 משתנה, אבל אין deadlock: בסוף no deadlock.

move(who) locks shelfA then shelfB. Two threads call it. The order between T1 and T2 changes, but there's no deadlock: finally no deadlock.

איך הפלט אמור להיראות?What should the output look like?
T1 moved a book
T2 moved a book
no deadlock
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: שני ה-threads משתמשים באותה מתודה, ולכן באותו סדר.Both threads use the same method, so the same order.
לפתרוןSolution
תרגילExercise 2

העברה בנקאית בלי deadlockA bank transfer without deadlock

transfer(from, to, amount) נועלת את שני החשבונות. כש-T1 מעביר x→y ו-T2 מעביר y→x, נעילה לפי from ואז to עלולה להיתקע. נעלו תמיד לפי id קטן קודם. מ-100 ו-100, אחרי 30 ו-10: 80 120.

transfer(from, to, amount) locks both accounts. When T1 moves x→y and T2 moves y→x, locking from then to can freeze. Always lock the smaller id first. From 100 and 100, after 30 and 10: 80 120.

איך הפלט אמור להיראות?What should the output look like?
80 120
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: Account first = from.id < to.id ? from : to;Account first = from.id < to.id ? from : to;
לפתרוןSolution
תרגילExercise 3

צייד באגים: from ואז toBug hunter: from then to

בגרסה הזו transfer נועלת from ואז to. ברוב ההרצות זה עובר, ולפעמים התוכנית קופאת לנצח (לכן לא הרצנו אותה). מצאו בסימולטור את הסדר שתוקע, ותקנו עם נעילה לפי id.

In this version transfer locks from then to. Most runs pass, and sometimes the program freezes forever (that's why we didn't run it). Find the freezing order in the simulator, and fix it by locking by id.

איך הפלט אמור להיראות?What should the output look like?
80 120
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: T1 נועל x ומחכה ל-y; T2 נועל y ומחכה ל-x.T1 locks x and waits for y; T2 locks y and waits for x.
לפתרוןSolution
תרגילExercise 4

tryLock מוותרtryLock gives up

כתבו את work מהתזכורת: נועלת first, ומנסה second עם tryLock(200, MILLISECONDS). אם לא הצליח: ... gave up: would have been a deadlock. תמיד משחררים ב-finally. לפחות thread אחד ידפיס gave up או ששניהם got both.

Write work from the refresher: lock first, and try second with tryLock(200, MILLISECONDS). If it fails: ... gave up: would have been a deadlock. Always release in finally. At least one thread prints gave up, or both print got both.

איך הפלט אמור להיראות?What should the output look like?
T2 gave up: would have been a deadlock
T1 gave up: would have been a deadlock
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: התוכנית מסתיימת תמיד, גם כשהיה deadlock פוטנציאלי.The program always ends, even when a deadlock was possible.
לפתרוןSolution
תרגילExercise 5

מדף, צעד 38: השאלה בין שני מדפיםShelf, step 38: lending between two shelves

פרויקט מלווהCompanion project

Shelf.lend(from, to) מעבירה ספר אחד בין מדפים, עם ReentrantLock לכל מדף, תמיד לפי id (הקטן קודם). שני threads מעבירים בכיוונים הפוכים. מ-home=3 ו-club=1: home=3 club=1.

Shelf.lend(from, to) moves one book between shelves, with a ReentrantLock per shelf, always by id (smaller first). Two threads move in opposite directions. From home=3 and club=1: home=3 club=1.

איך הפלט אמור להיראות?What should the output look like?
home=3 club=1
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: שני מנעולים מקוננים, כל אחד עם try/finally משלו.Two nested locks, each with its own try/finally.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

מנעול הוגן נגד הרעבהA fair lock against starvation

new ReentrantLock(true) משרת לפי סדר הגעה. main מחזיק את המנעול, ומפעיל T1, T2, T3 אחד אחרי השני (ומחכה שכל אחד ייכנס לתור עם hasQueuedThread). אחרי ששחרר: served in order: T1 T2 T3.

new ReentrantLock(true) serves in order of arrival. main holds the lock, and starts T1, T2, T3 one after another (waiting until each joins the queue with hasQueuedThread). After releasing: served in order: T1 T2 T3.

איך הפלט אמור להיראות?What should the output look like?
served in order: T1 T2 T3
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: מנעול לא הוגן היה יכול לתת למישהו "לעקוף בתור".An unfair lock could let someone "cut the line".
לפתרוןSolution
אתגרChallenge 2

לגלות deadlock מתוך התוכניתDetecting a deadlock from inside

שני threads (daemon, כדי שהתוכנית תוכל להסתיים) נכנסים ל-deadlock אמיתי. אחרי 300ms main שואל את ThreadMXBean.findDeadlockedThreads() ומדפיס deadlocked threads: 2. זה מה ש-jstack מראה מבחוץ.

Two threads (daemons, so the program can still end) enter a real deadlock. After 300ms main asks ThreadMXBean.findDeadlockedThreads() and prints deadlocked threads: 2. That's what jstack shows from outside.

איך הפלט אמור להיראות?What should the output look like?
deadlocked threads: 2
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: ManagementFactory.getThreadMXBean()ManagementFactory.getThreadMXBean()
לפתרוןSolution

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