Threads, race conditions, synchronized, atomics, ExecutorService, BlockingQueue and deadlock
90 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
90:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.
חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)
התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.
חלק ב: שאלות קודPart B: coding questions
שאלהQuestion 5
מונה מסונכרןA synchronized counter
כתבו class SafeCounter עם synchronized void increment() ו-synchronized int get(). ב-main ארבעה threads מגדילים אלף פעמים כל אחד, join לכולם, ומדפיסים 4000. בלי Atomic.
Write class SafeCounter with synchronized void increment() and synchronized int get(). In main four threads increment a thousand times each, join all of them, and print 4000. No atomics.
איך הפלט אמור להיראות?What should the output look like?
4000
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:synchronized על מתודה נועל את העצם this.synchronized on a method locks the object this.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) throws InterruptedException {
SafeCounter c =new SafeCounter();
Thread[] ts =newThread[4];
for (int i =0; i < ts.length; i++) {
ts[i] =newThread(() -> {
for (int k =0; k <1000; k++) {
c.increment();
}
});
ts[i].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println(c.get());
}
}
class SafeCounter {
privateint count;
synchronizedvoid increment() {
count++;
}
synchronizedint get() {
return count;
}
}
פלטOutput
4000
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (25 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.
שאלהQuestion 6
ספירת מילים במקבילCounting words in parallel
כתבו static int countWords(List<String> docs): כל מסמך נספר במשימה משלו ב-ExecutorService של 4 threads (Callable<Integer>), והתוצאות מחוברות מה-Future. מילה היא רצף בלי רווחים. main מדפיס 7.
Write static int countWords(List<String> docs): each document is counted in its own task in an ExecutorService of 4 threads (Callable<Integer>), and the results are added up from the Futures. A word is a run without spaces. main prints 7.
איך הפלט אמור להיראות?What should the output look like?
7
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 2:shutdown() ב-finally.shutdown() in a finally.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
publicclass Main {
staticint countWords(List<String> docs) throwsException {
ExecutorService pool =Executors.newFixedThreadPool(4);
try {
List<Future<Integer>> parts =newArrayList<>();
for (String doc : docs) {
parts.add(pool.submit(() -> doc.isBlank() ?0: doc.trim().split("\\s+").length));
}
int total =0;
for (Future<Integer> f : parts) {
total += f.get();
}
return total;
} finally {
pool.shutdown();
}
}
publicstaticvoidmain(String[] args) throwsException {
System.out.println(countWords(List.of("the night train", " ", "stops at every station")));
}
}
פלטOutput
7
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (25 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.
שאלהQuestion 7
פס ייצורA pipeline
כתבו static int pipeline(int n): thread יצרן מכניס 1 עד n ל-ArrayBlockingQueue בגודל 2, ואחריהם -1 ("גלולת רעל" שאומרת שנגמר). thread צרכן מוציא ומחבר עד שהוא מקבל -1. המתודה מחכה לשניהם ומחזירה את הסכום. main מדפיס 15.
Write static int pipeline(int n): a producer thread puts 1 to n into an ArrayBlockingQueue of size 2, followed by -1 (a "poison pill" saying it's over). A consumer thread takes and adds until it gets -1. The method waits for both and returns the sum. main prints 15.
איך הפלט אמור להיראות?What should the output look like?
15
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:put נחסם כשהתור מלא, take כשהוא ריק.put blocks when the queue is full, take when it's empty.
רמזHint 2:את הסכום מחזיקים ב-AtomicInteger או במערך של איבר אחד, כי lambda לא יכולה לשנות משתנה מקומי.Keep the sum in an AtomicInteger or a one-item array, because a lambda can't change a local variable.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (30 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.