Shared Mutability != public

Shared mutability is not restricted to public fields. You may be thinking “Gee, all my fields are private, so I have nothing to worry about,” but it’s not that simple.

A shared variable is accessed, for read or write, by more than one thread. On the other hand, a variable that’s never accessed by more than one thread—ever—is isolated and not shared. Shared mutable variables can really mess things up if we fail to ensure visibility or avoid race conditions. It’s rumored that shared mutability is the leading cause of insomnia among Java programmers.

Irrespective of access privileges, we must ensure that any value passed to other methods as parameters is thread safe. We must assume that the methods we call will access ...

Get Programming Concurrency on the JVM 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.