Last active
December 12, 2023 02:42
-
-
Save bobpoekert/3acc954ed24333d5319dcbad6185ca99 to your computer and use it in GitHub Desktop.
clojure thread local
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns thread-local | |
(import ThreadLocalThing)) | |
(defn make-thread-local | |
[generator] | |
(ThreadLocalThing. ::initial-val generator)) | |
(defmacro thread-local | |
[& body] | |
`(make-thread-local (fn [] ~@body))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import clojure.lang.IFn; | |
import clojure.lang.IDeref; | |
import java.lang.ThreadLocal; | |
public class ThreadLocalThing extends ThreadLocal implements IDeref { | |
final Object sentinelValue; | |
final IFn generator; | |
public ThreadLocalThing(Object sentinelValue, IFn generator) { | |
this.sentinelValue = sentinelValue; | |
this.generator = generator; | |
} | |
@Override | |
public Object initialValue() { | |
return this.sentinelValue; | |
} | |
public Object deref() { | |
Object res = this.get(); | |
if (res == this.sentinelValue) { | |
res = this.generator.invoke(); | |
this.set(res); | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. My implementation using proxy instead of a java class. Supports deref + swap!,reset!,compare-and-set!