23.4.3 Unsynchronized Mutable Data Sharing
First, we illustrate the dangers of sharing an object across threads without proper synchronization. In this example (Figs. 23.5–23.7), two Runnable
s maintain references to a single integer array. Each Runnable
writes three values to the array, then terminates. This may seem harmless, but we’ll see that it can result in errors if the array is manipulated without synchronization.
Class SimpleArray
A SimpleArray
object (Fig. 23.5) will be shared across multiple threads. SimpleArray
will enable those threads to place int
values into array
(declared at line 9). Line 10 initializes variable writeIndex
, which will be used to determine the array element that should be written to next. The constructor (lines ...
Get Java™ How To Program (Early Objects), Tenth 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.