Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mind-expanding thread weirdness

 
M Easter
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

http://codetojoy.blogspot.com/2007/05/easters-laws-of-concurrency.html

(*) 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
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
M Easter
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic