23.4.4 Synchronized Mutable Data Sharing—Making Operations Atomic

The output errors of Fig. 23.7 can be attributed to the fact that the shared object, SimpleArray, is not thread safeSimpleArray is susceptible to errors if it’s accessed concurrently by multiple threads. The problem lies in method add, which stores the value of writeIndex, places a new value in that element, then increments writeIndex. Such a method would present no problem in a single-threaded program. However, if one thread obtains the value of writeIndex, there’s no guarantee that another thread cannot come along and increment writeIndex before the first thread has had a chance to place a value in the array. If this happens, the first thread will be writing to the array based ...

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.