I am still new to Javascript. I am developing a simple page where I click a button fetching a value on a servlet and displays it. It works well, unless I click like crazy on the button. Sometimes, the displayed result is null.
I am wondering whether this is caused by simultaneous calls to the same following function:
function loadXMLDoc2(retr) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { $("#" + retr).button('option', 'label', xmlhttp.responseText); // document.getElementById(retr).innerHTML=xmlhttp.responseText; } } var param = "cmd=" + encodeURIComponent(retr); document.getElementById("TOP_LEFT").innerHTML = param; xmlhttp.open("GET","/WebFront/Asynclet?" + param,true); xmlhttp.send(null); }
Is Javascript thread-safe? And if not, how can I synchronize or isolate calls to this method?
Thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurring. Where as Synchronized means only one thread can operate at single time.
To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.
All are thread safe. There are no threads, JavaScript is single threaded, it's impossible for two javascript statements to run at the same time.
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
Other than HTML5 web workers (which are very tightly controlled and not apparently what you are asking about), Javascript in the browser is single threaded so regular Javascript programming does not have thread safety issues. One thread of execution will finish before the next one is started. No two pieces of Javascript are running at exactly the same time.
Things like ajax responses go through an event queue and are only executed when any other thread of execution has finished.
See Do I need to be concerned with race conditions with asynchronous Javascript? for more info.
For a specific discussion of ajax response callbacks see How does JavaScript handle AJAX responses in the background?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With