Synchronizing on an array. Does it synchronize on

2019-08-06 04:03发布

问题:

If I synchronize on an array, does this mean that I'm synchronizing on all the elements in it or am I synchronizing on the array object? If the latter is true, then how can I synchronize on all the elements in an array at once so that I can make sure non will be accessed while executing a certain block?

E.g. Lets say we have an array of bank accounts and we want to make sure no thread can access any account when a certain block of code is being executed.

回答1:

It synchronizes on the monitor for the array itself.

Even if you could synchronize on all the elements, that wouldn't ensure that they weren't accessed - because synchronization is only advisory.

The solution here is probably encapsulation: don't allow other code to see the array itself at all. That way you can control how other code is able to access the members of the array, via your own methods (like ArrayList does, for example).

Note that even if you do all of this, it won't stop other code from fetching the array element before your exclusive code starts running, and then using that reference while your exclusive code is running (e.g. mutating the object it refers to). You haven't really given us much information about what you're trying to do, but you may need to take a different approach.



回答2:

Java 9 handles memory differently and has more options for synchronizing on array elements. For a detailed technical explanation see "Using JDK 9 Memory Order Modes" http://gee.cs.oswego.edu/dl/html/j9mm.html

If this link goes away in the future, google "java varhandle" to learn more.