December 24, 2006

You don't know jack about thread-safety

All you hotshot programmers need to drop what you're doing and secure a copy of Java Concurrency in Practice. 50 pages into the book my face was frozen in pure horror, as Brian Goetz and his friends happily ran over everything I ever thought I knew about thread-safe programming.

What do you think the following code will print to the console?

public class NoVisibility {

    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread {
        public void run() {
            while (!ready) Thread.yield();
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().start();
        number = 42;
        ready = true;
    }
}

Unless your answer is "either zero, 42 or nothing at all" you really need to read the book before someone notices.

Comments

So is it generally interesting like Doug Lea's book? Or is it only on Java trivia?

Posted by kellan (#)

The problems and patterns discussed in the book are not specific to Java (the example I posted probably isn't either).

All code examples are in Java though. Since Java ships with more concurrency related helper classes than other languages you might find some of the examples difficult to translate.

Posted by Henning Koch [TypeKey Profile Page] (#)

I second Henning's motion.

Posted by Brian Goetz (#)

You heard the man :)

Posted by Henning Koch [TypeKey Profile Page] (#)

Post a comment

Thanks for signing in, . Now you can comment. (sign out)

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


Remember me?