My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Friday, June 15, 2007

Simplest JavaScript Deadlock

It's just another basic test to understand better JavaScript asyncronous queues and it could crash your browser or freeze them.

var loop = true,
block = setTimeout(function(){loop = false}, 1);
while(loop);


It's a deadlock, because while loop is waiting that condition is setted to false while timeout, the one who'll set that condition to false, is waiting while loop end to be executed.

THe same behaviour is expected with Ajax or every other async interaction.
This is JavaScript, have fun :-)

7 comments:

  1. so don't believe who say JavaScript is multi threading ;)

    ReplyDelete
  2. "Huh so don't use this? "

    This is an example of a typical method to itterate through a trees of data - people do it all the time.

    The example is just showing how things can go wrong - but in it's simplistic display it makes it quite apparent that there is an issue. A better real-life example might make things more relevent.

    Bill

    ReplyDelete
  3. I beg to differ, looks like a simple infinite loop. The while loop never looses control. What this does prove however, is that javascript is not multi-threaded since the timeout script will never get a chance to run.

    ReplyDelete
  4. What this does prove however, is that javascript is not multi-threaded since the timeout script will never get a chance to run.

    Ok Juanito, this was this post goal :-)

    However, usually a deadlock is created when one operation wait another one to be executed and vice-versa.

    Since JavaScript is single threading, it's really simple to create a "sort" of deadlock but your probably right, this deadlock example is not so clear (but with a single threading enviroment it's quite difficult to create a real deadlock example, isn't it?)

    ReplyDelete
  5. Yeah....thats true..but..only firefox cannot detect it and hangs...else...all browser can detect them and prompts warning...

    ReplyDelete
  6. i like your style of explaining. thank you very much and keep going on such interesting topics.

    ReplyDelete

Note: Only a member of this blog may post a comment.