Race free code?
I recently saw a reference to the term "race free code", but I've been unable to get a good description of what it means. The more perceptive amongst you will be able to guess my question by now... so why are elephants greyish? (And while answering that, could someone also explain what "race free" means.)
[314 byte] By [
EvilBroa] at [2007-11-27 2:09:36]

Imagine you have an instance variable called count:
++count;
System.out.println(count);
If multiple threads run this code then you have a potential race condition. I.e. thread 1 increments the count to 1 but before it calls println thread 2 increments the count again to 2. The result is that both threads print 2.
To make the code "race free" you could synchronize it:
synchronized(this) {
tempCount = ++count;
}
System.out.println(tempCount);
Now thread 1 will correctly print 1 and thread 2 will print 2.
Actually making race free code isn't that hard, per se. If your code only uses 1 thread, it will be race-free. Also, even if you have hundreds of threads if none of them share data or depend on other threads then this is race free.
The dual problem of "race condition" is "deadlock".
You can fix race conditions trivially by requiring synchronized access to all data.
But that will then, very likely, result in deadlock. (Thread 1 holds data X
and waits for data Y, and thread 2 holds data Y and waits for data X.
Both threads will wait forever)