Sundararajan's Weblog

  • Java
    November 9, 2005

Thread local storage in JavaScript

Guest Author

JSR 223 API allows exposing
multliple scopes (called "Bindings") to scripts.
ScriptEngine allows one or more
Bindings to be specified while evaluating scripts via
ScriptContext. Script engine will search these "scopes" while looking for global variables.

How can we have thread local storage in JavaScript?

Java program that executes JavaScript (by eval) can expose
different ENGINE_SCOPE bindings
for each Java thread. This way the script global variables accessed from script executing in different Java threads would
be different.

But, what if the script itself creates Java thread(s)? In that case, script can make use of java.lang.ThreadLocal
directly as shown below:

var tls = (function () {
var map = new Object();
return new JSAdapter() {
__has__: function(name) {
return map[name] != undefined;
__get__: function(name) {
if (map[name] != undefined) {
return map[name].get();
} else {
return undefined;
__put__: sync(function(name, value) {
if (map[name] == undefined) {
var tmp = new java.lang.ThreadLocal();
map[name] = tmp;
} else {
__delete__: function(name) {
if (map[name] != undefined) {

With the above code, we can write:

tls.x = 10;
print(tls.x); // prints 10
// create another thread and start it
var th = new java.lang.Thread(
function () {
tls.x = 'hello';
print(tls.x); // prints 'hello'
print(tls.x); // prints 10 -- value is thread local.

We can easily create multiple thread local variables by adding more properties
to "tls" object. Also, we can use "tls" object in JavaScript with statement
so that the scope uses thread local variables:

with(tls) {
print(x); // prints thread local x in each thread

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.