8.2. Concurrency Problems

An interviewer can quickly learn how well you understand multithreaded programming by asking you to solve one or two classic problems involving multiple threads of execution.

8.2.1. Busy Waiting

NOTE

Explain the term "busy waiting" and how it can be avoided.

This is a simple problem, but one with important performance implications for any multithreaded application.

Consider a thread that spawns another thread to complete a task. Assume that the first thread needs to wait for the second thread to finish its work, and that the second thread terminates as soon as its work is done. The simplest approach is to have the first thread wait for the second thread to die:

Thread task = new TheTask();
task.start();

while( task.isAlive() ){
    ; // do nothing
}

This is called busy waiting because the waiting thread is still active, but it's not actually accomplishing anything. It's "busy" in the sense that the thread is still executed by the processor, even though the thread is doing nothing but waiting for the second thread to finish. This actually "steals" processor cycles away from the second thread (and any other active threads in the system), cycles that could be better spent doing real work.

Busy waiting is avoided using a monitor or a semaphore, depending on what's available to the programmer. The waiting thread simply sleeps (suspends itself temporarily) until the other thread notifies it that it's done. In Java, any shared object can be used as a notification ...

Get Programming Interviews Exposed: Secrets to Landing Your Next Job, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.