Meaningless Drivel is fun!
The moose likes Threads and Synchronization and the fly likes mind-expanding thread weirdness Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "mind-expanding thread weirdness" Watch "mind-expanding thread weirdness" New topic

mind-expanding thread weirdness

M Easter
Ranch Hand

Joined: Feb 11, 2007
Posts: 133
Here's a question. Given this code:

or, better yet, this code. (the posts below will explain things better)

Under what circumstances can y == 20 and yet x does not == 10 ?

So as not to give it away immediately, the answer is in the next posts.

Bonus: can you compare & contrast the 2 code snippets? (I couldn't apparently, since I had an error in the original post LOL)
[ May 06, 2007: Message edited by: M Easter ]

M Easter
Software Composer -
M Easter
Ranch Hand

Joined: Feb 11, 2007
Posts: 133
One answer to the question is:

if the code specified is not synchronized, then it is feasible that, at a particular point in time in the view of another thread, y == 20 but x != 10.

The reason, as explained in Java Concurrency in Practice (*), is "reordering" -- the JVM is allowed to reorder the operations of instructions so long as the changes are not detectable in the current thread. However, the changes may well be detectable in other threads (without proper synchronization).

Pretty wild stuff.... This book has led me to define my "3 laws of concurrency", which essentially state that if you don't understand threading issues, you will have bugs. And if you do understand threading issues, you'll have bugs.

If you are interested:

(*) I have no affliation with the book or its author. It just blows my mind.
[ May 06, 2007: Message edited by: M Easter ]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
In the original code snippet, it looks like x, y, z are local variables. In which case each thread has its own stack, with its own local variables, and no way to observe out-of-order behavior in other threads' data. Whereas if x, y, z were instance variables, then different threads could be accessing the same data, leading to the behavior you describe in your second post.

I agree that multiple threads can create some very bizarre effects, tough to wrap the brain around.
[ May 06, 2007: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
M Easter
Ranch Hand

Joined: Feb 11, 2007
Posts: 133
Oops! Excellent point, Jim...

that's what I get for not wanting to plagarize an example from the book :roll:

I will edit the original post but major kudos for catching this
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: mind-expanding thread weirdness
It's not a secret anymore!