Question

In C, I can allocate a register for a variable, for example:

register int i = 0;

I am aware that Java is an interpreted language, and is many many abstractions away from the CPU.

Is there any mechanism available to even request (and if the architecture doesn't allow it, so what) that my variable remains in a register instead of moving to cache or main memory?

I don't suppose there is any way, but I have been pleasantly surprised before.

Thank you,

Was it helpful?

Solution

No, there's no way to request this in Java. However, there are some things that you can do that will prevent a register from being used, such as applying the volatile modifier to a member variable.

OTHER TIPS

register in C does not put a variable to register. It simply gives the compiler the hint, that it would probably be good to put it into a register.

In Java there is no equivalent.

If it's used enough in a short space that making it a register int would be worthwhile, then the hotspot compiler should be able to figure that out itself.

In fact, the hotspot compiler should be able to do a better job than the C/C++ compiler, because it has more information to work with. C/C++ compilers have to guess; HotSpot can measure.

There's no equivalent in Java. Even in C there is no guarantee that the variable will be stored in a register and compilers are free to ignore it.

In Java, the method will be interpreted until the hotspot JIT heuristically determines that it needs to be compiled. For compiled code it uses a coloring algorithm to assign variables and temporary values to registers, or write to/from RAM in the case of register overflow.

I am aware that Java is an interpreted language, and is many many abstractions away from the CPU.

You pretty much answered your own question there :-)

But seriously, in general, write your code as clearly and simply as you can, and the JVM will do what it can to treat your code right.

You can create an annotation called @register but the JVM will definitely ignore it. e.g.

@register int i = 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top