Synchronized Statements


Prerequisites

This Magercise shows a case where synchronizing on an object works more conveniently than using synchronzied methods. Here a Speaker object wants to get a lock on an AnnounceBox and hold it across several method calls, thus avoiding the interference of other threads. This technique is also useful when accessing objects that are provided by others and don't have any built-in thread safety.

Work Location

Perform all work for this magercise in VisualAge project MageLang Magercises, package magercises.Synchronized Statements.

If this project does not appear in your Workspace add it from the repository (if it exists there) or create a new project using this name.

Tasks

Perform the following tasks:

  1. Create a Speaker class that extends Thread and as its task repeatedly makes calls to the announce method of AnnounceBox to say a sentence, one call for each word. The code in the SynchStmtApplet suggests the necessary interface for the Speaker class. Do not attempt synchronization. In order to maximize the chance of contention between two Speakers, have them sleep for a small random amount of time after completing the sentence. Each Speaker should try to say its sentence five times.

  2. Compile and run the applet to demonstrate contention for the AnnounceBox.

  3. Change the Speaker class to synchronize on the AnnounceBox before writing to it using a synchronized statement.

  4. Compile and run the applet, both sentences should be uninterrupted. AnnounceBox.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.