Skip to content

Commit

Permalink
Try locking only
Browse files Browse the repository at this point in the history
  • Loading branch information
mk authored and zampino committed Oct 16, 2023
1 parent d133010 commit 365c3e5
Showing 1 changed file with 2 additions and 16 deletions.
18 changes: 2 additions & 16 deletions src/nextjournal/markdown.clj
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,22 @@

(def ^Context ctx (.build context-builder))

(def CTXLock (Object.))
;; Avoid multithreading access to context
;; - https://www.graalvm.org/latest/reference-manual/js/Multithreading/#multithreading-with-java-and-javascript
;; - https://github.com/oracle/graaljs/blob/1d96acfa10cbea9e27e78800c2b82cdbad262791/graal-js/src/com.oracle.truffle.js.test.threading/src/com/oracle/truffle/js/test/threading/ConcurrentAccess.java#L173-L240

(defmacro with-context-enter [c & body]
`(try (.enter ~c) ~@body (finally (.leave ~c))))

(defmacro with-context-lock [c & body]
`(locking CTXLock (with-context-enter ~c ~@body)))

#_(macroexpand '(with-context-lock ctx
(.execute bla)))

(def ^Value MD-imports
;; Contructing a `java.io.Reader` first to work around a bug with graal on windows
;; see https://github.com/oracle/graaljs/issues/534 and https://github.com/nextjournal/viewers/pull/33
(let [source (-> (io/resource "js/markdown.mjs")
io/input-stream
io/reader
(as-> r (Source/newBuilder "js" ^Reader r "markdown.mjs")))]
(with-context-enter ctx
(locking ctx
(.. ctx
(eval (.build source))
(getMember "default")))))

(def ^Value tokenize-fn (.getMember MD-imports "tokenizeJSON"))

(defn tokenize [markdown-text]
(let [^Value tokens-json (with-context-lock ctx
(let [^Value tokens-json (locking ctx
(.execute tokenize-fn (to-array [markdown-text])))]
(json/read-str (.asString tokens-json) :key-fn keyword)))

Expand Down

0 comments on commit 365c3e5

Please sign in to comment.