views:

129

answers:

4

I was reading a Sun's tutorial on Concurrency.

But I couldn't understand exactly what memory consistency errors are? I googled about that but didn't find any helpful tutorial or article about that.

I know that this question is a subjective one, so you can provide me links to articles on the above topic.

It would be great if you explain it with a simple example.

+3  A: 

You can read up about Read After Write (RAW), Write after Write(WAW) and Write After Read (WAR) hazards to learn more about this topic. These hazards refer to pipelined processses but it really is the same problem that occurs with multi threading. It basically means that two different threads are updating the same location in memory and if you depend on these updates in a certain order then you may be surprised to see that you cannot guarantee the order in which the updates occur.

For example, if you have two statements:

  x = y + z;
  r = x + z;

in a single thread then you have no problem because the value of r will always be consistent. In multiple threads however, it is possible or either statement to occur first and the value of r is harder to predict.

Vincent Ramdhanie
+1  A: 

Hm. They are basically talking about "visibility problems" and "re-ordering problems" (that terminology is more common at least in Java IMO). I think this link:http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile explains what the tutorial is talking about, using more common terms (perhaps sun tried to use "easier" vocabulary or something).

Enno Shioji
+1 for the link
Yatendra Goel
+2  A: 

Basically in absence of any synchronization threads can see a different value of a simple field. Consider this example:

class Foo
{
  int bar = 0;

  void unsafeCall ( )
  {
    final Foo thisObj = this;

    Runnable r = new Runnable ( )
    {
      public void run ( )
      {
        thisObj.bar = 1;
      }
    }

     Thread t = new Thread( );

     t.start( );
     Thread.sleep( 1000 );

     // May print bar = 0
     System.out.println( "bar = " + bar );
  }
}

The simplest way of avoiding memory consistency error is to declare bar field to be volatile.

This forcing of threads to recheck the memory is called memory barrier. One other example of memory barrier is a synchronized method/block.

Alexander Pogrebnyak
A: 

If you'd like to get a deeper understanding of shared memory consistency models, I'd refer you to the following tutorial.

http://rsim.cs.uiuc.edu/~sadve/Publications/computer96.pdf

reprogrammer