I wonder if there is a way to synchronize objects/methods in JavaScript in a similar way that you can do it in Java. I am developing an interface for the new WebSocket in html5 and need a way to match outgoing requests with incoming responses. Therefore I'm saving the requests (with a unique id) in an array on the client side and then I iterate through the array when I receive a response looking for the matching request.
A problem that might occur on the client side is if I have multiple timers that are making requests to the server independently of each other. If a the request function is inserting a "request-reference" into the array at the same time as the respond-listener is iterating through the array it's bound to break!
So how do I solve this problem? My initial thoughts was to simply synchronize the array as one could have done in Java (putting a lock on the object and force the other functions to wait) but I have found no syntax of how I would do this in JavaScript.
Javascript runs in a single thread in the browser, so there is no need to synchronize.
See here for details. See this SO question and answers as well (Why doesn’t JavaScript support multithreading?).
Related
We have some data stored in localstorage and we are using window.setInterval() to regularly update it every minute. In this interval we are continuously reading and writing the data.
Is it possible that concurrency issues can occur because we're using setInterval(), as multiple tabs can modify the data in localstorage simultaneously?
Edit 1: Explaining the scenario in detail:
Each tab is writing some data to localstorage against a key (say xyz) and also setInterval(), present in the running javascript, continuously checks the xyz key data. If some data exists against the key, then the setInterval callback sends it to the back end. Each tab running the same script will read the xyz key and append some data to the existing value after performing some logic.
I doubt that a concurrency issue may occur, like one tab may be reading the xyz key and adding data to the local storage and another tab might be doing the same thing at the same time. Now both will try to send the data at the same time, hence I may receive the same data 2 times in the back end.
Is it possible that concurrency issues can occur because we're using SetInterval() as multiple tabs can modify the data in local storage simultaneously?
There are two aspects to this:
Are getItem/setItem (and their accessor equivalents) atomic?
Can different tabs/windows doing a series of getItem/setItem calls have those calls interleaved?
On #1, surprisingly, the storage specification seems not to address this head-on. In a "Note" it says:
Note
This specification does not require that the above methods wait until the data has been physically written to disk. Only consistency in what different scripts accessing the same underlying list of key/value pairs see is required.
...which suggests to me that getItem/setItem will be atomic — that is, the datum you're getting/setting won't get corrupted if two threads call getItem/setItem at literally the same time.
Re #2, I don't think there are any guarantees, no. If each tab/window has its own thread, then in theory two of those threads could simultaneously enter the block of code doing these updates. Sometimes, tabs/windows share a single thread, in which case you'd be safe, but...
I would avoid having lots of different entries in localStorage that need to be updated in a coordinated way. Instead, I'd use a single entry with a structure. I usually use JSON for that. So getting the data looks like this:
let data = JSON.parse(localStorage.getItem("the-data")) || {/*...default structure here...*/};
and saving it looks like this:
localStorage.setItem("the-data", JSON.stringify(data));
so you could do
let data = JSON.parse(localStorage.getItem("the-data")) || {/*...default structure here...*/};
// ...modify the various parts of `data`...
localStorage.setItem("the-data", JSON.stringify(data));
then you're left with a simple race between the threads (the last one to write wins), but the stored data will be consistent.
In my opinion, it really depends on what you consider be "concurrency issues".
For the case of writing, I don't believe that you will have any issue, the browser will manage well what and when should write to localstorage. Your data will not be corrupted in the process.
For the case of reading, I believe that you will have problems when you are reading from the Tab1 but the last write was from the Tab2.
Added after Edit: There is one more possibility, you can try to find out which page/tab of yours is active (of your page) and then activate the timer only at active tabs, then lowering chance of occuring concurrency.
Here is https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API api for visibility checks.
I'm using the setTimeout() function in javascript to allow a popup that says "loading" to be shown while I'm parsing some xml data. I found that at small enough delay values (below 10ms) it doesn't have time to show it before the browser freezes for a moment to do the actual work.
At 50ms, it has plenty of time, but I don't know how well this will translate to other systems. Is there some sort of "rule of thumb" that would dictate the amount of delay necessary to ensure a visual update without causing unnecessary delay?
Obviously, it'll depend on the machine on which the code is running etc., but I just wanted to know if there was anything out there that would give a little more insight than my guesswork.
The basic code structure is:
showLoadPopup();
var t = setTimeout(function()
{
parseXML(); // real work
hideLoadPopup();
}, delayTime);
Thanks!
UPDATE:
Turns out that parsing XML is not something that Web Workers can usually do since they don't have access to the DOM or the document etc. So, in order to accomplish this, I actually found a different article here on Stack Overflow about parsing XML inside a Web Worker. Check out the page here.
By serializing my XML object into a string, I can then pass it into the Web Worker through a message post, and then, using the JavaScript-only XML parser that I found in the aforementioned link, turn it back into an XML object within the Web Worker, do the parsing needed, and then pass back the desired text as a string without making the browser hang at all.
Ideally you would not ever have to parse something on the client side that actually causes the browser to hang. I would look into moving this to an ajax request that pulls part of the parsed xml (child nodes as JSON), or look at using Web Workers or a client side asynchronous option.
There appears to be no "rule-of-thumb" for this question simply because it was not the best solution for the problem. Using alternative methods to do the real meat of the work was the real solution, not using a setTimeout() call to allow for visual update to the page.
Given options were:
HTML 5's new Web Worker option (alternative information)
Using an AJAX request
Thanks for the advice, all.
I have a node server for loading certain scripts that can be written by anyone. I understand that when I fire up my Node server, modules load for the first time in the global scope. When one requests a page, it gets loaded by the "start server" callback; and I can use all the already loaded modules per request. But I haven't encountered a script where global variables get changed during request time and affects every single other instance in the process (maybe there is).
My question is, how safe is it, in terms of server crashing, to alter the global data? Also, suppose that that I have written a proper locking mechanism that will "pause" the server for all instances for a very short amount of time until the proper data is loaded.
Node.js is single threaded. So it's impossible for two separate requests to alter a global variable simultaneously. So in theory, it's safe.
However, if you're doing stuff like keep user A's data temporarily in a variable and then when user A later submits another request use that variable be aware that user B may make a request in between potentially altering user A's data.
For such cases keeping global values in arrays or objects is one way of separating user data. Another strategy is to use a closure which is a common practice in callback-intensive or event/promise oriented libraries such as socket.io.
When it comes to multithreading or multiprocessing, message passing style API like node's built-in cluster module has the same guarantees of not clobbering globals since each process have its own global. There are several multithreading modules that's implemented similarly - one node instance per thread. However, shared memory style APIs can't make such guarantees since each thread is now a real OS thread which may preempt each other and clobber each others memory. So if you ever decide to try out one of the multithreading modules, be aware of this issue.
It is possible to implement fake shared memory using message passing though - sort of like how we do it with ajax or socket.io. So I'd personally avoid shared memory style multithreading unless I really, really need to cooperatively work on a very large dataset that would bog down message passing architectures.
Then again, remember, the web is a giant message passing architecture with the messages being HTML and XML and json. So message passing scales to Google size.
I am currently implementing a graph visualisation tool using lift on the server side and d3 ( a javascript visualisation framework) for all the visualisation. The problem I have is that in the script I want to get session dependent data from the server.
So basically, my objective is to write lift-valid ajax callbacks in a static js script.
What I have tried so far
If you feel that the best solution is one that I already tried feel free to post a detailed answer telling me how to use it exactly and how it completely solves my problem.
Write the ajax callback in another script using lift and call it from the main script
This solution, which is similar to a hidden text input is probably the more likely to work. However it is not elegant and it would mean that I would have to load a lot of scripts on load, which is not really conveniant.
This seems to be one of the prefered solutions in the lift community as explained in this discussion on the mailing list.
REST interface
Usually what one would do to get data from a javascript function in lift is to create a REST interface. However this interface will not be linked to any session. This is the solution I got from my previous question: Get json data in d3 from lift snippet
Give function as argument of script
Another solution would be to give the ajaxcallback as an argument of the main script called to generate my graph. However I expect to have a lot of callbacks and I don't want to have to mess with the arguments of my script.
Write the whole script in lift and then serve it to the client
This solution can be elegant, however my script is very long and I would really prefer that it remainss static.
What I want
On client side
While reviewing the source code of my webpage I found that the callback for an ajaxSelect is:
<select onchange="liftAjax.lift_ajaxHandler('F966066257023LYKF4=' + encodeURIComponent(this.value), null, null, null)" name="F96606625703QXTSWU" id="node_delete" class="input">
Moreover, there is a variable containing the state of the page in the end of the webpage:
var lift_page = "F96606625700QRXLDO";
So, I am wondering if it is possible to simulate that my ajaxcall is valid using this liftAjax.lift_ajaxHandler function. However I don't know the exact synthax to use.
On server side
Since I "forged" a request on client side, I would now like to get the request on client side and to dispatch it to the correct function. This is where the LiftRules.dispatch object seems the best solution: when it is called, all the session management has been made (the request is authentified and linked to a session), however I don't know how to write the correct piece of code in the append function.
Remark
In lift all names of variables are changed to a random string in order to increase the security, I would like to have the same behavior in my application even if that will probably mean that I will have to "give" the javascript these values. However an array of 15 string values is still a better tradeoff than 15 functions as argument of a javascript function.
Edit
While following my research I found this page : Mapping server functions to client actions which somehow explains the goal of named functions even if it stil didn't lead me to a working solution.
Quick Answer
Rest in Lift does not have to be stateless. If you register your RestHelper with LiftRules.dispatch.append, then it will be handled statefully and Session information will be available through the S object as usual.
Long Answer
Since you seem interested, and it's come up on SO before, here's a more detailed explanation of how server-side functions are registered and called in Lift. If you haven't worked with Lift for some time, look away. What follows should not in any way be used to evaluate Lift or its complexity. This is purely library developer level stuff and a majority of Lift users go about their development blissfully unaware of it.
How it works
When you create stateful callbacks, typically by using the methods within the SHtml object, what you are really doing is registering objects of type S.AFuncHolder within the context of the users session, each with a unique ID. The unique ID that was generated during this process is what you're seeing when you come across a pattern like F96606625700QRXLDO. When data is submitted, via form post, ajax, or whatever, Lift will check the request for these function ids and execute the associated function if they exist. There are several helpers that provide more specific types of AFuncHolder, like S.SFuncHolder (accepts a single string query parameter) and S.BinFuncHolder (parameter is multipart form data) but they all return Any and behind the scenes Lift will collect those return values to create the proper type of response. A JsCmd, for instance, will result in a JavaScriptResponse that executes the command. You can also return a LiftResponse directly.
How to use it
AFuncHolders are registered using the S.fmapFunc method. You'd call it like this
S.fmapFunc(SFuncHolder({ (str: String) =>
doSomethingAwesomeWithAString(str)
}))(id => <input type="text" name={id} value=""/>)
The first parameter is your function, wrapped in the proper *FuncHolder type and the second parameter is a function that takes the generated id and outputs something. The something that gets output is what you will include on the page. It should somehow result in the id being sent to the server as a query parameter so that your function is executed.
Putting it all together
You could use the above to make your own Ajax calls, but when Lift makes an ajax call there are a few other considerations:
1) Most browsers only allow so many simultaneous connections to a given domain. Three seems to be the magic number.
2) AFuncHolders will often close over the scope of the snippet they are contained within and if multiple ajax requests are handled at once, each in its own thread, bad things can happen.
To combat these issues, the liftAjax.lift_ajaxHandler function queues each ajax request, ensuring that only one at a time is sent to the server.
The drawback to this approach is that it can make it difficult to make an Ajax call where the result needs to be passed to a callback. JQuery autocomplete, for instance, provides a callback function when input changes that accepts a list of matches. If you are manually calling LiftAjax.lift_ajaxHandler though, you can provide your own callback functions for success & error and I would recommend that you look at the source of those functions in your browser for more information on how they work.
There's actually more to it, like how Lift restores RequestVars on ajax callbacks (which is where the lift_page comes in, but that's about all I'm prepared to explain over coffee on a Saturday morning :)
Good luck with your app!
I am new to javascript/jquery.
I have a simple question one of java script function is running and wanted to see the thread id for that thread.
In java we do like
Thread.getID();//in java
which will print the thread id of running thread.
In the similar way what is the function we use to get the running thread id in javscript.
Actually what i want is..
In my JavaScript, I have a listener which is listening to the channel. When ever there is a message in the channel, the callback method is called and processes the data. So here I am trying to see how it works in that way.. Let's say there are 10 messages in the channel and for each message the callback is called.
Let's say the callback method is running for a message "a" and while processing the data for the message "a", it got another message "b". Will the callback method for "b" be called once the processing for message "a" is complete?
I wanted to check this by printing the thread number in the callback function which tells whether it is running sequentially (one thread) or multiple threads. That is why I was trying to print the thread id. Thanks for your responses.
Thanks,
Swati
JavaScript is single threaded. So this wouldn't apply to JavaScript.
However, it is possible to spawn multiple threads through a very limited Worker interface introduced in HTML5 and is already available on some browsers. From an MDC article,
The Worker interface spawns real OS-level threads, and concurrency can cause interesting effects in your code if you aren't careful. However, in the case of web workers, the carefully controlled communication points with other threads means that it's actually very hard to cause concurrency problems. There's no access to non-thread safe components or the DOM and you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.
What do you need this for?
For most things in JavaScript there's one thread, so there's no method for this, since it'd invariable by "1" where you could access such information. There are more threads in the background for events and queuing (handled by the browser), but as far as your code's concerned, there's a main thread.
Java != JavaScript, they only share 4 letters :)
Aside from the name, Javascript is totally unrelated to Java. Javascript does not have threads that you can access.
In javascript the scripts run in a browser thread, and your code have no access to that info, actually your code have no idea whatsoever how it's being run. So NO! there's no such thing in javascript.