Multithread and JavaScript Context Management

Like JavaScript, a GraalJS context is single-threaded, and only a single thread can access a GraalJS context at a time. However, in the Clojure/Java world, multithreading is the nature. Therefore one may expected to have a GraalJS per thread, or manage multiple contexts on their own.

This library provides ways to do that.

Binding context/*context*

js4clj gets it context by reading context/*context*. It is of clojure.lang.IDeref type and you can use your own context by dynamically binding it.

(binding [context/*context* (atom (-> (context/default-builder)
                                      #_"customize the builder"
                                      (.build)))]
  ;; code here
  )
  • It will override context/*context-per-thread* (introduced in the next section).
  • context/reinitialize-context! won’t work as expected if you bound *context*.

context/*context-per-thread*

If you bind context/*context-per-thread* to true (without binding *context*). @context/*context* will return the thread local context, create one in case it isn’t already existed. (Note: you can customize the context by binding context/*customize-builder* and context/*after-init-hook*)