donsasikumar
donsasikumar

Reputation: 31

Java is using volatile keyword memory efficient?

If using 1 volatile variable, does it turn off cpu caching in for other related non volatile variables as well?

Upvotes: 2

Views: 185

Answers (3)

Stephen C
Stephen C

Reputation: 719229

It doesn't "turn off" caching. But yes it does typically cause a flush of other pending writes (when you write a volatile) or at least some cache invalidation (when you read a volatile) ... and both of these use extra memory bandwidth, and impact on performance.

Consider this example:

public volatile int foo;
public int bar;

/* thread 1 */

bar = 1; // A
foo = 1; // B

/* thread 2 */
System.err.println("foo = " + foo);  // C
System.err.println("bar = " + bar);  // D

The JLS says that A happens-before B and C happens-before D. If C in thread 2 is subsequent to B in thread 1, then B happens-before C, and therefore A happens-before D.

If A happens-before D then the value written to bar at A must be available as bar at D ... assuming that nothing else wrote to bar in the meantime.

It is implementation specific how this is actually achieved. But there are certainly affects on cached data ... including cached copies of non-volatile fields.

Assuming a typical memory architecture, and assuming that thread 1 and thread 2 don't share caches, this means that:

  • both foo and bar must be flushed to main memory by thread 1 at B, and
  • at C any of thread 2's cached copies of foo and bar must be discarded.

My understanding is that this is typically implemented using cache invalidate and cache flush instructions.


The bottom line is that use of volatile can have significant performance impact on a multi-core system due to the extra memory traffic that it generates.

Upvotes: 1

radai
radai

Reputation: 24192

no, it only prevents that variable from being loaded up to cpu cache and modified there. more precisely, it forces the cpu to flush its cache after accessing the volatile field. see here for more complate details

Upvotes: 2

Mikkel Løkke
Mikkel Løkke

Reputation: 3749

The volatile keyword has nothing to do with memory. It is a concurrency issue.

Edit The volatile keyword has nothing to do with memory efficiency. It is a concurrency issue.

Upvotes: 0

Related Questions