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]
# 1
A race condition is when the output of two operations depends on the order they occur in basically. http://en.wikipedia.org/wiki/Race_condition There are links at the bottom of that article that talk about how to avoid them.
hunter9000a at 2007-7-12 2:00:13 > top of Java-index,Java Essentials,New To Java...
# 2

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.

YoGeea at 2007-7-12 2:00:13 > top of Java-index,Java Essentials,New To Java...
# 3
I see. Thanks. I feel sort of silly though for not trying "race condition" in google (I tried enough other things without success).
EvilBroa at 2007-7-12 2:00:14 > top of Java-index,Java Essentials,New To Java...
# 4
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.
tjacobs01a at 2007-7-12 2:00:14 > top of Java-index,Java Essentials,New To Java...
# 5

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)

KathyMcDonnella at 2007-7-12 2:00:14 > top of Java-index,Java Essentials,New To Java...