Imagine that we have a 1000 objects of the same type scattered across the memory (they were created at different times and other objects have been created in between).
We have an array which holds references to each of the 1000 objects.
If we iterate over the array sequentially, what will be prefetched into the cache of the CPU? Only the references which the array holds or will those references be dereferenced and the objects loaded into the cache as well?
Does Java (the JVM) implement some kind of software prefetching? If not, are there libraries which provide software prefetching?
After some research, the most common JVM implementation (HotSpot) used to support prefetching. But this has been removed, since there is no practicle use for them. Thanks to @apangin for the link to the bug report.
As @markspace mentioned, objects get re-arranged for easier access during collections - this is called "compacting", and is present in the default GC used by HotSpot. You shouldn't need to worry about such underlying details, as the VM handles that for you.
You've probably heard of "Stop-The-World" - this occurs when the object graph is in an inconsistent state. Objects are being moved around, so a thread might access an object thats no longer there. There are some GC implementations that are considered "pauseless", such as the Shenandoah GC, which use a forwarding pointer to allow a thread to access an object that was recently moved.
The point being, you don't need to worry about where an object may be located in memory, or how far the location is from another object. The VM was designed to take care of these decisions for you.
So, are objects prefetched from an array of reference? You really shouldn't worry about it. You use Java to not have to care about these underlying details.
If you're REALLY interested in such details (maybe there's some strange bug you're encountering), as I've mentioned before, it's implementation specific, and you'd have to be specific about which implementation you're referring to.
Although, like I said before, it's Java; stop worrying about things you don't need to worry about. I can't emphasize this enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With