Alternative to mutex for race conditions in localStorage


I saw this quote in a recent standard document:

"The use of the storage mutex to avoid race conditions is currently
considered by certain implementors to be too high a performance
burden, to the point where allowing data corruption is considered
preferable. Alternatives that do not require a user-agent-wide
per-origin script lock are eagerly sought after"

I wanted to point out that CouchDB has a very nice solution to this
problem that would be very applicable to a client-side localStorage
container in HTML5 (since couch implements JSON for storage, couch's
http line spec is probably 100% transferable to your case).

I believe the relevant spec for CouchDB is here:

The basic concept is that instead of locking mutexes per transaction
(which has a high performance burden), CouchDB deals in document
versions. The basic rules for document versions are:

1) All documents have built-in system keys: "id" and "version"
2) You can submit a new document without a version # but if it already
exists, the submission fails.
2a) If you don't provide an id # for a new doc, the local storage
creates one for you.
3) If you submit the same document with the version # corresponding to
the version in the local storage, the old version is overwritten.
4) If you submit a document with a version number which doesn't match
the one in local storage, the update fails.
5) Whenever you create or update a document, you are returned an id
and version number in the response so you can maintain version state
in local code.

With those 5 rules, you can have high performance local storage
without too great a burden (in terms of locking/mutex/atomic handling)
on the storage engine. This pushes some logic for "locking" into the
client apps, but what is nice is that single-thread/simple client apps
can ignore this altogether. Sophisticated client apps must implement
some version handling. This is a great alternative to locking or
mutexes, b/c for the vast majority of web development cases, there are
no locking issues. But when a locking issue does arise, it's very easy
to handle it (and the system prevents you from overwriting data that
has changed since your last update - which is the real point to
mutexes in web programming, in my opinion).

I'm sure the CouchDB community would be happy to give you more info on
their approach, and hopefully this input is useful. Feel free to write
to me with additional questions.

Thanks for your work on the problem,
Steve Midgley

p.s. I'd also expect that some browser implementers could potentially
simply implement CouchDB itself as the local storage engine behind an
html5 interface, as it's designed to run in very low footprint
environments. It's already running in a few mobile phone environments
I believe..

Received on Sunday, 13 March 2011 21:12:07 UTC