Using Synchronized Methods


Prerequisites

This Magercise shows one way to use synchronized methods to protect data structures in a concurrent environment. It also shows how to use the join method as a way to synchronize threads.

Given a simple stack, designed to operate in a non-concurrent context, make it safe to use in a concurrent context by modifying its methods to be synchronized. Create a subclass of Thread, StackStuffer, to repeatedly push and pop items on the stack. Call the threadDone method of SyncTest after that to have the stack printed to the output TextArea.

Here it is appropriate to have the StackStuffer class inherit from Thread, as it has no other inheritance requirements, and it wants access to its thread methods to remain public.

Note that even though there is the potential for corruption of the stack in a concurrent environment, it can be hard to force it in an example due to differences in implementations and code use. Non-preeemptive environments will not do a thread switch unless the current thread blocks on something or yields. For this example, the code that is sensitive is in the push method, and as this is a small amount of code, even on a pre-emptive system it may be hard to force corruption of the stack. Nevertheless it can happen and structures such as these must be protected.

Work Location

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

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. Make all appropriate methods in SimpleStack synchronized.

  2. Create a new subclass of Thread, StackStuffer, to repeatedly push ten strings on the stack, then pop five of them off. Add a call to SyncTest.stackDone after that.

  3. In the start method of SynchTest, create a SimpleStack and two new instances of StackStuffer with strings to push onto the stack, then start them off.

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.