Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are objects prefetched from an array of references in Java?

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.

Question

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?

like image 955
PaperTsar Avatar asked Jul 05 '15 19:07

PaperTsar


1 Answers

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.

A little deeper into compacting..

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.

The final answer

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.

like image 195
Vince Avatar answered Oct 23 '22 00:10

Vince