Does Java change the value of only the modified fields from cache?

Viewed 60

According to my understanding, when a write-back happens from the cache to the main memory, it will write the entire cache block. This might include bytes/words which were not modified as well, as the dirty bit is set on a cache block as a whole.

In this, I am assuming that CPU architectures generally don't track 'dirtiness' on a byte-level. Feel free to correct my assumption if all the present architectures do track on a byte-level.

Say, two java fields, say a and b reside side by side and have the same tag. So, while caching, they would be placed in the same cache block.

Say there's a thread running in a core which updates only the value of a, but not b. Then, would actually the value of both a and b be updated in the main memory from the cache? Or does java have something to ensure that only the value of a is updated, given that only a is changed?

Does java even have a role here? Or is it all dependent on the CPU architecture?

My exact concern

Assume initially, a=1, b=1 Say we have two threads T1 and T2. T1 does only one thing, it sets a=2. Similarly, T2 does b=2.

Assume we have a multi-core environment with cores C1 and C2 running T1 and T2 respectively. Both cache the values a=1, b=1.

Say T1 finishes first. Cache of C1 is written back. So, now, in the main memory, a=2, b=1. Now, T2 finishes. Now when cache is written back, does it set a=1, b=2 because C2 had a=1 in its cache?

Or does Java have any guarantee against this?

Assume that no Happens Before/After relationship is established. No synchronization or volatile or anything else of that sort.

Feel free to correct any of my assumptions.

1 Answers

Nitpicking: Writes in theory don't need to go to main memory; they could stay in the cache indefinitely depending on the cache coherence algorithm used.

The problem you are referring to, is called word tearing and the JVM should protect against it.

Check out the following links:

I'm not familiar with other architectures, but on the X86 loads and stores can be done at the byte level. An n-byte field, will always be n-byte aligned; so it will never be split over 2 cache-lines. And since a boolean in Java, is stored in a byte, word tearing can't happen on the X86.

Related