JMM: Cache invalidation vs happens before rules

In the last 2 month I have had 2 discussion with other developers about the Java Memory Model (JMM) about some visibility issues and after some discussion I figured out they were still using the ‘cache invalidation’ approach instead of the happens before model the JMM is expressed in. One of the problems with the former approach is that according to that approach, the following example doesn’t contain a visibility problem.

final Object a = new Object();
final Object b = new Object();
int x = 0;

void foo(){
	synchronized( a ){
		x = 10;
	}
}

void bar(){
	synchronized( b ){
		println( x );
	}
}

According to the cache invalidation approach, the cache is invalidated as soon as the lock(b) is acquired, forcing all changes made prior to the release of lock(a), to become visible in the current thread. It doesn’t matter if the locks are not the same. According to the JMM and the monitor rule (one of the happens before rules), there is no happens before relation between the write of x and the read of x, because the locks are not the same. So according to that model there is a visibility problem.

Conclusion? Stop reasoning about caches/cache-invalidations and start reasoning with happens before rules. That is the easiest way to predict what could happen.

Advertisements

2 Responses to JMM: Cache invalidation vs happens before rules

  1. Xebia Blog says:

    […] using a read and write under a lock (should be the same lock) should also fix the […]

  2. […] lock elision through Escape Analysis: if an object is confined to a single thread, a lock has no additional value (even not for the JMM) […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: