Is there any software prefetching instructions in Java language or JVM, like __builtin_prefetch which is available in GCC
1 Answers
One interesting thing is that Hotspot JVM actually does support prefetch!
It treats Unsafe.prefetchRead()
and Unsafe.prefetchWrite()
methods as intrinsics and compiles them into corresponding CPU instructions.
Unfortunately, sun.misc.Unsafe
does not declare such methods. But, if you add the following methods to Unsafe.java, recompile it and replace Unsafe.class inside rt.jar (or just add -Xbootclasspath/p
JVM argument) you would be able to use prefetch intrinsics in your application.
public native void prefetchRead(Object o, long offset);
public native void prefetchWrite(Object o, long offset);
public static native void prefetchReadStatic(Object o, long offset);
public static native void prefetchWriteStatic(Object o, long offset);
I doubt this could help much in real applications, but if you'd like to play with it, I can provide more details.
Here is a compiled patch to JDK 8 that enables prefetch methods: download
Usage example:
long[] array = new long[100*1024*1024];
// ...
sun.misc.Unsafe.prefetchReadStatic(array, 50*1024*1024);
UPDATE
Unsafe.prefetch*
intrinsics are completely removed in JDK 9:
Note read/write prefetch support was implemented as an experiment to see if JDK library code could use it for performance advantages. However, the results of the experiment did not indicate this was worthwhile. As a consequence there are no corresponding prefetch native method declarations in sun.misc.Unsafe.

- 92,924
- 10
- 193
- 247
-
Good. 1) According to http://www.java-gaming.org/index.php?topic=27010.0 , they are present in hotspot intrinsic. So there is no need to recompile anything. Am I right? – mahmood Mar 29 '14 at 08:36
-
Yes, Hotspot JVM already knows about the intrinsics, but they should be declared in the class library. So you'll need to either patch `rt.jar` (replace Unsafe.class) or prepend the [modified Unsafe.class](https://docs.google.com/file/d/0B7LUxTf0AV-faDBWRzE3UzVFa2M) to boot classpath using `-Xbootclasspath/p` flag. – apangin Mar 29 '14 at 20:39
-
Can you comment on `-XX:AllocatePrefetchLines` JVM option? Does it enable prefetch? – neverov Nov 14 '14 at 16:47
-
@neverov All `AllocatePrefetch*` options are related to emitting `prefetch` instructions right after object allocation in Java Heap. This is controlled by `-XX:AllocatePrefetchStyle` option which is ON by default. `AllocatePrefetchLines` and `AllocateInstancePrefetchLines` control how far (in number of cache lines) to prefetch after the address of allocated object, for an array or an object respectively. – apangin Nov 18 '14 at 11:56