From Java Concurrency in Practice
Publishing one object may indirectly publish others. If you add a Secret to the published knownSecrets set, you’ve also published that Secret, because any code can iterate the Set and obtain a reference to the new Secret. Similarly, returning a reference from a nonprivate method also publishes the returned object. UnsafeStates in Listing 3 . 6 publishes the supposedly private array of state abbreviations.
class UnsafeStates { private String[] states = new String[] { "AK", "AL" ... }; public String[] getStates() { return states; } }
Publishing states in this way is problematic because any caller can modify its contents. In this case, the states array has escaped its intended scope, because what was supposed to be private state has been effectively made public.
In the example, what is the correct way to write getStates
method, so that the states array doesn't escape its intended scope?
Is it correct that the quote about escape isn't directly related to multithreading and synchronization?
Thanks.