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.
שני מדפים, סדר אחדTwo shelves, one order
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static final Object shelfA = new Object();
static final Object shelfB = new Object();
static void move(String who) {
synchronized (shelfA) {
synchronized (shelfB) {
System.out.println(who + " moved a book");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> move("T1"));
Thread t2 = new Thread(() -> move("T2"));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("no deadlock");
}
}T1 moved a book T2 moved a book no deadlock
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
העברה בנקאית בלי deadlockA bank transfer without deadlock
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
סדר מנעולים הפוך: deadlockOpposite lock order: deadlock
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) throws InterruptedException {
Account x = new Account(1, 100);
Account y = new Account(2, 100);
Thread t1 = new Thread(() -> Bank.transfer(x, y, 30));
Thread t2 = new Thread(() -> Bank.transfer(y, x, 10));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(x.balance + " " + y.balance);
}
}
class Account {
final int id;
int balance;
Account(int id, int balance) {
this.id = id;
this.balance = balance;
}
}
class Bank {
static void transfer(Account from, Account to, int amount) {
Account first = from.id < to.id ? from : to;
Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
from.balance -= amount;
to.balance += amount;
}
}
}
}80 120
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: from ואז toBug hunter: from then to
תזכורת: מה ביקשוReminder: the task
בגרסה הזו 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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
סדר מנעולים הפוך: deadlockOpposite lock order: deadlock
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) throws InterruptedException {
Account x = new Account(1, 100);
Account y = new Account(2, 100);
Thread t1 = new Thread(() -> Bank.transfer(x, y, 30));
Thread t2 = new Thread(() -> Bank.transfer(y, x, 10));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(x.balance + " " + y.balance);
}
}
class Account {
final int id;
int balance;
Account(int id, int balance) {
this.id = id;
this.balance = balance;
}
}
class Bank {
static void transfer(Account from, Account to, int amount) {
Account first = from.id < to.id ? from : to;
Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
from.balance -= amount;
to.balance += amount;
}
}
}
}80 120
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
tryLock מוותרtryLock gives up
תזכורת: מה ביקשוReminder: the task
כתבו את 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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
סדר מנעולים הפוך: deadlockOpposite lock order: deadlock
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static final ReentrantLock a = new ReentrantLock();
static final ReentrantLock b = new ReentrantLock();
static void work(String name, ReentrantLock first, ReentrantLock second) {
first.lock();
try {
sleep(50);
if (second.tryLock(200, TimeUnit.MILLISECONDS)) {
second.unlock();
System.out.println(name + " got both");
} else {
System.out.println(name + " gave up: would have been a deadlock");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
first.unlock();
}
}
static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> work("T1", a, b));
Thread t2 = new Thread(() -> work("T2", b, a));
t1.start();
t2.start();
t1.join();
t2.join();
}
}T2 gave up: would have been a deadlock T1 gave up: would have been a deadlock
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 38: השאלה בין שני מדפיםShelf, step 38: lending between two shelves
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
Shelf home = new Shelf("home", 3);
Shelf club = new Shelf("club", 1);
Thread a = new Thread(() -> Shelf.lend(home, club));
Thread b = new Thread(() -> Shelf.lend(club, home));
a.start();
b.start();
a.join();
b.join();
System.out.println(home + " " + club);
}
}
class Shelf {
private static int nextId = 0;
final int id = nextId++;
final String name;
final ReentrantLock lock = new ReentrantLock();
int books;
Shelf(String name, int books) {
this.name = name;
this.books = books;
}
static void lend(Shelf from, Shelf to) {
Shelf first = from.id < to.id ? from : to;
Shelf second = first == from ? to : from;
first.lock.lock();
try {
second.lock.lock();
try {
if (from.books > 0) {
from.books--;
to.books++;
}
} finally {
second.lock.unlock();
}
} finally {
first.lock.unlock();
}
}
@Override
public String toString() {
return name + "=" + books;
}
}home=3 club=1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מנעול הוגן נגד הרעבהA fair lock against starvation
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
ReentrantLock fair = new ReentrantLock(true);
StringBuilder order = new StringBuilder();
fair.lock();
Thread[] ts = new Thread[3];
for (int i = 0; i < 3; i++) {
String name = "T" + (i + 1);
ts[i] = new Thread(() -> {
fair.lock();
try {
order.append(name).append(" ");
} finally {
fair.unlock();
}
});
ts[i].start();
while (!fair.hasQueuedThread(ts[i])) {
Thread.onSpinWait();
}
}
fair.unlock();
for (Thread t : ts) {
t.join();
}
System.out.println("served in order: " + order.toString().trim());
}
}served in order: T1 T2 T3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לגלות deadlock מתוך התוכניתDetecting a deadlock from inside
תזכורת: מה ביקשוReminder: the task
שני 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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
סדר מנעולים הפוך: deadlockOpposite lock order: deadlock
הפתרון המלא והפלט שלוFull solution and its output
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class Main {
public static void main(String[] args) throws InterruptedException {
Object a = new Object();
Object b = new Object();
Thread t1 = new Thread(() -> {
synchronized (a) {
pause();
synchronized (b) {
System.out.println("never printed");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (b) {
pause();
synchronized (a) {
System.out.println("never printed");
}
}
});
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
Thread.sleep(300);
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] stuck = mx.findDeadlockedThreads();
System.out.println("deadlocked threads: " + (stuck == null ? 0 : stuck.length));
}
static void pause() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}deadlocked threads: 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.