Java Reference
In-Depth Information
pool-1-thread-1 wrote 1 to element 0.
Next write index: 1
pool-1-thread-2 wrote 11 to element 1.
Next write index: 2
pool-1-thread-2 wrote 12 to element 2.
Next write index: 3
pool-1-thread-2 wrote 13 to element 3.
Next write index: 4
pool-1-thread-1 wrote 2 to element 4.
Next write index: 5
pool-1-thread-1 wrote 3 to element 5.
Next write index: 6
Contents of SimpleArray:
[1, 11, 12, 13, 2, 3]
Fig. 23.8
|
Class that manages an integer array to be shared by multiple threads with
synchronization. (Part 2 of 2.)
Line 20 declares method
add
as
synchronized
, making all of the operations in this
method behave as a single, atomic operation. Line 22 performs the first suboperation—
storing the value of
writeIndex
. Line 35 defines the second suboperation, writing an ele-
ment to the element at the index
position
. Line 39 increments
writeIndex
. When the
method finishes executing at line 41, the executing thread implicitly
releases
the
Simple-
Array
lock, making it possible for another thread to begin executing the
add
method.
In the
synchronized
add
method, we print messages to the console indicating the
progress of threads as they execute this method, in addition to performing the actual oper-
ations required to insert a value in the array. We do this so that the messages will be printed
in the correct order, allowing us to see whether the method is properly synchronized by
comparing these outputs with those of the previous, unsynchronized example. We con-
tinue to output messages from
synchronized
blocks in later examples for demonstration
purposes only; typically, however, I/O
should not
be performed in
synchronized
blocks,
because it's important to minimize the amount of time that an object is “locked.”
[
Note:
Line 27 in this example calls
Thread
method
sleep
(for demo purposes only) to empha-
size the unpredictability of thread scheduling. You should never call
sleep
while
holding a lock in a real application
.
]
Performance Tip 23.2
Keep the duration of
synchronized
statements as short as possible while maintaining the
needed synchronization. This minimizes the wait time for blocked threads. Avoid per-
forming I/O, lengthy calculations and operations that do not require synchronization
while holding a lock.
Synchronization
In a
producer/consumer relationship
, the
producer
portion of an application generates
data and
stores it in a shared object
, and the
consumer
portion of the application
reads data