In Java, can I decide where is my field stored: in register, cache or RAM?

Viewed 138

I know that it is done automatically - the more frequently a piece of data is accessed, the closer to the processor it is stored. But can I somehow influence their placement with Java syntax? Volatile, the way I understand it, puts data in level 3 cache or RAM since it's visible to all the threads, is that right?

3 Answers

No, Java syntax does not allow direct access to the hardware. The Java language and virtual machine specification is the contract governing how Java code is interpreted - and it is explicitly written to target a Virtual Machine instead of an actual one.

From Section 1.2:

The Java Virtual Machine is the cornerstone of the Java platform. It is the component of the technology responsible for its hardware- and operating system-independence, the small size of its compiled code, and its ability to protect users from malicious programs.

The Java Virtual Machine is an abstract computing machine. Like a real computing machine, it has an instruction set and manipulates various memory areas at run time. It is reasonably common to implement a programming language using a virtual machine; the best-known virtual machine may be the P-Code machine of UCSD Pascal.

There is no need for a Java VM to even have accessible registers or caches. From the point of view of the specs, a Turing Machine could very well implement a conformant Java VM.

Java works differently regarding optimisations to a large degree. You the the developer say what to do in your code. Then, at runtime, the just in time compiler looks at what is going on, and then (if necessary) translates "slow" java byte code into highly optimized machine code.

In other words: the JIT decides what code is worth optimizing. That might include optimized "data layouting".

But as said: you as a developer have "no say" in this.

You can't control this behavior.

If the CPU reads a field of an object the object is pulled into the L1d. This is independent of the field being volatile or not.

It doesn't matter if a field is accessed only once or many times; it will still end up in the L1d. Unless you have a non temporal load/store; but this behavior is not accessible from Java.

Volatile prevents reordering of instructions on both compiler and CPU/memory-sub-system level. In case of the X86, the volatile read you get for free (acquire semantics) due to the TSO memory model of X86. The volatile write is implemented by stopping the front-end from executing loads till the store buffer has been drained. This prevents the reordering of older stores with newer loads to a different address.

For more information see: https://shipilev.net/blog/2014/on-the-fence-with-dependencies/

Related