Oracle
1Z0-819 · Question #41
Given the two classes: public class Resource { public Worker owner; public synchronized boolean claim(Worker worker) { if (owner == null) { owner = worker; return true; } else return false; } public…
The correct answer is D. The code does not compile. See the full explanation below for the reasoning.
Question
Given the two classes:
public class Resource {
public Worker owner;
public synchronized boolean claim(Worker worker) {
if (owner == null) {
owner = worker;
return true;
}
else return false;
}
public synchronized void release() {
owner = null;
}
}
public class Worker {
public synchronized void work(Resource... resources) {
for (int i = 0; i < 10; i++) {
while (!resources[0].claim(this)) { }
while (!resources[1].claim(this)) { }
// do work with resources
resources[1].release();
resources[0].release();
}
}
}
And given this fragment:
Worker w1 = new Worker();
Worker w2 = new Worker();
Resource r1 = new Resource();
Resource r2 = new Resource();
new Thread(() -> {
w1.work(r1, r2);
}).start();
new Thread(() -> {
w2.work(r2, r1);
}).start();
Which describes the fragment?
Options
- AIt throws IllegalMonitorStateException.
- BIt is subject to livelock.
- CIt is subject to livelock.
- DThe code does not compile.
How the community answered
(24 responses)- A17% (4)
- B8% (2)
- C4% (1)
- D71% (17)
Community Discussion
No community discussion yet for this question.