I’m working on a Javascript reverse singly-linked list implementation. That is, a linked-list which instead of being referenced by a variable storing the head object, which contains a link to the next and so on, is stored in a tail variable referring to the list’s last node, each of which contains a link to the previous node. The gist of the implementation is below:
// A reversed linked list of the sequence 1, 2, 3
var tail = {
value: 3,
previous: {
value: 2,
previous: {
value: 1,
previous: null
}
}
};
The code to push a new node onto the end of this list (tail) looks like this:
tail = {
value: 4,
previous: tail
};
Here’s a demo: http://jsbin.com/ajixip/1/
The problem that I foresee with this push is a race condition that can occur between the retrieval of the curent value of tail and setting the new value.
Consider, for example, a user triggering an event, which pushes a new value to the tail of the list. Let’s call the time when the value of tail is retrieved and assigned to the key previous Time A and let’s call the point when tail is set to the new object Time B. If another push was made to the list between Time A and Time B, its previous would be the tail from Time A and assuming it would assign itself to tail after Time B, the first node push would be lost.
I’m puzzled by how such a race condition could be avoided. My initial thought was to implement a lock that prevented concurrent pushes, but there probably is some clever JS wizardry that avoids this. Any wizards care to share some of this magic?
Thanks!
Since Javascript is not multithreaded, you have no problem in the example you gave. This is, for all intents and purposes today, an atomic operation.