Monday, August 30, 2010

Java concurrency is unsafe

Have you ever wondered how stuff in java.util.concurrent works?

I know I am late. It was in early 2000 (if not before that) when Doug Lea had published his Concurrent Programming in Java and had described what later became JSR 166 and then finally part of JDK 1.5 in 2004. Still better late than never.

I actually wanted to find out just a few things. I wondered how they provided the full semantic of happens-before as it works in volatile and synchronized but on the API level. I wondered if I would still find the volatile and synchronized and wait/notify buried down in the implementation details or would there be something else.

I did not look into the original Doug Lea's source code but I what I found in the latest JDK implementation made me smile.

They're using sun.misc.Unsafe to do the atomic changes and suspend enqueued threads (it's called parking). The sun.misc.Unsafe is native all over the place and, as you can tell from its name, is considered unsafe. It's not really Java per se.

Do you still think Java concurrency is safe? :)

1 comment:

Anonymous said...

Um, "Unsafe" doesn't mean "Unreliable" in this case. It means, "It would be unsafe for your code to depend on this class because we reserve the right to change its API or take it away in any future release of the JRE."