Great book about parallel programming
Great book about parallel programming

Just found this really good book about parallel programming.

Although I haven't read the entire book (I'm working on that) it's clear to me that not only is it written in a appealing way, it also seams to be rather complete.

I found this book just as I am looking into code that can be used as an example of why parallel programming is hard: programmers that do not understand machines make it so. Really, you would suspect that a programmer nowadays would know better than to do something like:

    1: public class Example {
    2:         private static boolean readOnce = false;
    3:         // XPTO is some kind of complex class.
    4:         private static XTPO complexObject = null; 
    6:         public static XPTO doSomething () {
    7:                 if (!Example.test) {
    8:                         readOnce = true;
    9:                         complexObject = new XPTO ();
   10:                 }
   11:                 return complexObject;
   12:         }
   13: }

The issue here arises form checking a variable to decide or not to create the new XPTO instance. Picture this scenario:

  1. thread A is calls the method doSomething and finds the field readOnce to be false, entering the if block;
  2. before the thread A executes line 08 is interrupted and another thread (lets call it thread B ) also calls the doSomething method;
  3. thread B is continues its execution and gets a XPTO instance, that is at that time the same instance that the instance of the class Example is pointing to with the field complexObject;
  4. at this moment thread B is interrupted by the scheduler, and eventually thread A is resumed, executing line 8 and forward;
  5. thread A creates a new XPTO instance and the field complexObject now points to a new instance, not to the one that was previously created by thread B.

The state of the application is now undefined as, although the programmer tried to guarantee that the same object of type XPTO was returned by the doSomething method, there are two different instances of the class XPTO.

This is, of course, a rather classic and very simple example. Yet I found such things abundantly in the code that I am working with now (yes, poor me).