My unexperience with concurrency is quite clear, and I’m looking here for some help.
I was writing a multithreaded application in Java while I was assailed by a doubt. Please look at this sample code (mixing pseudocode and Java):
Thead 1 body (portion):
/* It creates and starts thread Thread 2 */
if (!thread2.taskCompleted)
thread2.wait();
/* continue execution... */
Thead 2 body:
class Thread2 extends Thread {
volatile boolean taskCompleted = false;
public void run() {
/* It executes a complex task... */
taskCompleted = true;
notifyAll(); // notify waiting threads
}
}
My concern is simple as that: what happens if the statements are executed in that order:
- Thread 1 starts Thread 2
- Thread 2 does some stuff, but doesn’t complete the task
- Thread 1 reads taskCompleted as false
- Thread 2 completes the task, raises the taskCompleted flag, and notifies (nobody)
- Thread 1 starts waiting. And never ends.
Please let me know if you have any ideas and/or it is a well-known scenario (exact duplicate?)
The usage of the
taskCompletedflag andwait()/nofiyAll()must be protected by a lock to avoid the scenario you describe.and