forked from clj-python/libpython-clj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjvm_handle.clj
70 lines (52 loc) · 1.82 KB
/
jvm_handle.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(ns libpython-clj2.python.jvm-handle
"Conversion of a jvm object into an integer and back. Used for storing handles
on python proxies."
(:require [libpython-clj2.python.protocols :as py-proto]
[libpython-clj2.python.gc :as pygc]
[libpython-clj2.python.ffi :as py-ffi])
(:import [java.util.concurrent ConcurrentHashMap]
[java.util UUID]))
(defonce ^{:private true
:tag ConcurrentHashMap}
jvm-handle-map (ConcurrentHashMap.))
(defn identity-hash-code
^long [obj]
(long (System/identityHashCode obj)))
(defn make-jvm-object-handle
^long [item]
(let [^ConcurrentHashMap hash-map jvm-handle-map]
(loop [handle (identity-hash-code item)]
(if (not (.containsKey hash-map handle))
(do
(.put hash-map handle item)
handle)
(recur (.hashCode (UUID/randomUUID)))))))
(defn get-jvm-object
[handle]
(.get ^ConcurrentHashMap jvm-handle-map (long handle)))
(defn remove-jvm-object
[handle]
(.remove ^ConcurrentHashMap jvm-handle-map (long handle))
nil)
(defn py-self->jvm-handle
^long [self]
(long (py-proto/get-attr self "jvm_handle")))
(defn py-self->jvm-obj
^Object [self]
(-> (py-self->jvm-handle self)
get-jvm-object))
(defn py-self-set-jvm-handle!
[self hdl]
(py-proto/set-attr! self "jvm_handle" (long hdl))
nil)
(defmacro py-global-delay
"Create a delay object that uses only gc reference semantics. If stack reference
semantics happen to be in effect when this delay executes the object may still be
reachable by your program when it's reference counts are released leading to
bad/crashy behavior. This ensures that can't happen at the cost of possibly an object
sticking around."
[& body]
`(delay
(py-ffi/with-gil
(with-bindings {#'pygc/*stack-gc-context* nil}
~@body))))