Skip to content

Commit 66cb158

Browse files
author
Anass Rach
committed
Adding concurrent question!
1 parent c42f729 commit 66cb158

1 file changed

Lines changed: 37 additions & 1 deletion

File tree

_data/quiz/questions.yml

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,4 +590,40 @@
590590
- "Runtime exception"
591591
correct: 1
592592
explanation: "submit(Runnable) returns a Future<?> whose get() returns null upon successful completion. submit(Callable<T>) returns a Future<T> whose get() returns the callable result. The output is: 'Runnable executed' (from the Runnable), then 'null' (from f1.get()), then 'Callable executed' (from f2.get()) - all printed consecutively without newlines since print() is used."
593-
category: "Concurrency"
593+
category: "Concurrency"
594+
595+
- question: "What is the output of this ReentrantLock code?"
596+
code: |
597+
import java.util.concurrent.*;
598+
import java.util.concurrent.locks.*;
599+
600+
public class FamilyGathering {
601+
private Lock dinnerLock = new ReentrantLock();
602+
603+
public void joinDinner() {
604+
dinnerLock.lock(); // f1
605+
if (dinnerLock.tryLock()) { // f2
606+
System.out.print("Eating dinner!");
607+
}
608+
dinnerLock.unlock();
609+
}
610+
611+
public static void main(String[] args) {
612+
try (var service = Executors.newFixedThreadPool(2)) {
613+
FamilyGathering family = new FamilyGathering();
614+
for (int i = 0; i < 2; i++)
615+
service.submit(() -> family.joinDinner());
616+
}
617+
System.out.print("Family dinner complete");
618+
}
619+
}
620+
options:
621+
- "Eating dinner!Family dinner complete"
622+
- "Eating dinner!Eating dinner!Family dinner complete"
623+
- "Family dinner complete"
624+
- "Program hangs and prints only: Eating dinner!"
625+
- "Compilation error"
626+
- "Runtime exception"
627+
correct: 3
628+
explanation: "This program demonstrates a ReentrantLock bug that causes a deadlock. When the first thread calls dinnerLock.lock() at f1, it acquires the lock. Then at f2, dinnerLock.tryLock() succeeds because ReentrantLock allows the same thread to acquire the lock multiple times (reentrant behavior). So 'Eating dinner!' prints once. However, the thread acquired the lock twice (once at f1, once at f2) but only calls unlock() once. This means the lock is never fully released - it still has a hold count of 1. When the first thread exits, the lock remains held, causing the second thread to wait indefinitely at its dinnerLock.lock() call. The program hangs and never prints 'Family dinner complete' because the ExecutorService cannot shut down with a blocked thread."
629+
category: "Concurrency"

0 commit comments

Comments
 (0)