Java Multitasking  «Prev 

Synchronization super add Element

Why synchronization is good

This application adds an utterance to the queue by calling the queue's addElement() method:


Programmers who use addElement() might not know how it is implemented. It might, for example, be implemented as five separate operations:
  1. Fetch the queue.
  2. Create a new queue that is one element longer.
  3. Copy the elements from the old queue to the new queue.
  4. Add the new element to the new queue.
  5. Replace the old queue with the new queue.

Now, certainly, this might not be the most efficient way to go (for example, one faster design is to increase the queue in chunks rather than one at a time), but the point is that calling addElement() is not necessarily one machine instruction. Any number of things could be occurring within this call.
What would happen if speaker 1 added an element and got as far as the fourth step in the list above when speaker 2, running as a separate thread, preempts to add an utterance? If speaker 2 made it through all five steps before speaker 1 was allowed to continue, speaker 1 would overwrite the queue and speaker 2's utterance would never be heard by the audience.
What we need here is a good way to help tell Java how to juggle competing threads.