Just found this really good book about parallel programming.
- Title: Is Parallel Programming Hard, And, If So, What Can You Do About It?
- Editor: Paul E. McKenney
- Publisher: kernel.org
- Year: 2011
- URL: http://kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html
- License: open source
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;
5:
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:
- thread A is calls the method
doSomethingand finds the fieldreadOnceto be false, entering the if block; - before the thread A executes line 08 is interrupted and another thread (lets call it thread B ) also calls the
doSomethingmethod; - thread B is continues its execution and gets a
XPTOinstance, that is at that time the same instance that the instance of the classExampleis pointing to with the fieldcomplexObject; - at this moment thread B is interrupted by the scheduler, and eventually thread A is resumed, executing line 8 and forward;
- thread A creates a new
XPTOinstance and the fieldcomplexObjectnow 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).