Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים.
Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors.
מונה בטוח, ארבעה threadsA safe counter, four threads
תזכורת: מה ביקשוReminder: the task
Counter עם synchronized על increment ועל get. ארבעה threads, כל אחד 10,000 פעמים. הדפיסו תמיד 40000.
Counter with synchronized on increment and get. Four threads, 10,000 times each. Always print 40000.
סימולציה: אתם מחליטים איזה 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
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable job = () -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
Thread t3 = new Thread(job);
Thread t4 = new Thread(job);
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println(counter.get());
}
}
class Counter {
private int count = 0;
synchronized void increment() {
count++;
}
synchronized int get() {
return count;
}
}40000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
בלוק synchronizedA synchronized block
תזכורת: מה ביקשוReminder: the task
שני threads מוסיפים כל אחד 1000 מספרים ל-ArrayList משותפת. ArrayList לא בטוחה ל-threads: עטפו את ה-add ב-synchronized (lock) על עצם פרטי, והדפיסו תמיד 2000.
Two threads each add 1000 numbers to a shared ArrayList. ArrayList isn't thread-safe: wrap the add in synchronized (lock) on a private object, and always print 2000.
סימולציה: אתם מחליטים איזה 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.ArrayList;
import java.util.List;
public class Main {
private static final List<Integer> items = new ArrayList<>();
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 1000; i++) {
synchronized (lock) {
items.add(i);
}
}
};
Thread a = new Thread(job);
Thread b = new Thread(job);
a.start();
b.start();
a.join();
b.join();
System.out.println(items.size());
}
}2000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: עדכונים אבודיםBug hunter: lost updates
תזכורת: מה ביקשוReminder: the task
התוכנית מהתזכורת מדפיסה מספר שונה בכל הרצה, ובדרך כלל פחות מ-200,000. תקנו את Counter כך שתמיד יודפס 200000.
The program from the refresher prints a different number each run, usually less than 200,000. Fix Counter so it always prints 200000.
סימולציה: אתם מחליטים איזה 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++ בלי הגנה: נסו לאבד עדכוןcount++ unprotected: try to lose an update
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable job = () -> {
for (int i = 0; i < 100000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}
class Counter {
private int count = 0;
synchronized void increment() {
count++;
}
synchronized int get() {
return count;
}
}200000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עשרה אנשים, שלושה עותקיםTen people, three copies
תזכורת: מה ביקשוReminder: the task
ל-Shelf יש 3 עותקים. 10 threads קוראים ל-lend(). הבדיקה וההורדה באותה מתודה synchronized, ולכן תמיד: lent 3, refused 7, left 0.
Shelf has 3 copies. 10 threads call lend(). The check and the decrement are in the same synchronized method, so it's always: lent 3, refused 7, left 0.
סימולציה: אתם מחליטים איזה 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.
בדיקה ופעולה בתוך מנעולCheck and act inside a lock
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) throws InterruptedException {
Shelf shelf = new Shelf(3);
Thread[] people = new Thread[10];
for (int i = 0; i < people.length; i++) {
people[i] = new Thread(shelf::lend);
people[i].start();
}
for (Thread p : people) {
p.join();
}
System.out.println("lent " + shelf.lent() + ", refused " + shelf.refused() + ", left " + shelf.copies());
}
}
class Shelf {
private int copies;
private int lent = 0;
private int refused = 0;
Shelf(int copies) {
this.copies = copies;
}
synchronized void lend() {
if (copies > 0) {
copies--;
lent++;
} else {
refused++;
}
}
synchronized int lent() {
return lent;
}
synchronized int refused() {
return refused;
}
synchronized int copies() {
return copies;
}
}lent 3, refused 7, left 0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter
תזכורת: מה ביקשוReminder: the task
LoanCounter סופר השאלות לפי כותר ובסך הכול. ארבעה דלפקים (threads) משאילים כל אחד 500 פעם, לסירוגין Dune ו-Emma. snapshot() מחזיר עותק. הדפיסו {Dune=1000, Emma=1000} total 2000.
LoanCounter counts loans per title and in total. Four desks (threads) lend 500 times each, alternating Dune and Emma. snapshot() returns a copy. Print {Dune=1000, Emma=1000} total 2000.
סימולציה: אתם מחליטים איזה 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.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws InterruptedException {
LoanCounter loans = new LoanCounter();
Runnable desk = () -> {
for (int i = 0; i < 500; i++) {
loans.lend(i % 2 == 0 ? "Dune" : "Emma");
}
};
Thread[] desks = {new Thread(desk), new Thread(desk), new Thread(desk), new Thread(desk)};
for (Thread d : desks) {
d.start();
}
for (Thread d : desks) {
d.join();
}
System.out.println(loans.snapshot() + " total " + loans.total());
}
}
class LoanCounter {
private final Map<String, Integer> byTitle = new TreeMap<>();
private int total = 0;
synchronized void lend(String title) {
byTitle.merge(title, 1, Integer::sum);
total++;
}
synchronized int total() {
return total;
}
synchronized Map<String, Integer> snapshot() {
return new TreeMap<>(byTitle);
}
}{Dune=1000, Emma=1000} total 2000יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
static synchronizedstatic synchronized
תזכורת: מה ביקשוReminder: the task
מונה static ומתודה static synchronized void visit() (נועלת את המחלקה). ארבעה threads × 10,000 קריאות. הדפיסו תמיד 40000.
A static counter and a static synchronized void visit() method (it locks the class). Four threads × 10,000 calls. Always print 40000.
סימולציה: אתם מחליטים איזה 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
public class Main {
static int visits = 0;
static synchronized void visit() {
visits++;
}
public static void main(String[] args) throws InterruptedException {
Thread[] ts = new Thread[4];
for (int k = 0; k < ts.length; k++) {
ts[k] = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
visit();
}
});
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println(visits);
}
}40000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מנעול שנכנסים אליו שובA lock you can re-enter
תזכורת: מה ביקשוReminder: the task
transferIn היא synchronized וקוראת ל-deposit (גם synchronized) פעמיים. בגלל שהמנעול reentrant אין תקיעה. מ-100, שני threads מעבירים 50 ו-25 (וכל העברה עולה 1): הדפיסו 173.
transferIn is synchronized and calls deposit (also synchronized) twice. Because the lock is reentrant nothing gets stuck. From 100, two threads transfer 50 and 25 (each transfer costs 1): print 173.
סימולציה: אתם מחליטים איזה 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
public class Main {
public static void main(String[] args) throws InterruptedException {
Account acc = new Account(100);
Thread a = new Thread(() -> acc.transferIn(50));
Thread b = new Thread(() -> acc.transferIn(25));
a.start();
b.start();
a.join();
b.join();
System.out.println(acc.balance());
}
}
class Account {
private int balance;
Account(int balance) {
this.balance = balance;
}
synchronized void deposit(int amount) {
balance += amount;
}
synchronized void transferIn(int amount) {
deposit(amount);
deposit(-1);
}
synchronized int balance() {
return balance;
}
}173
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.