-
Notifications
You must be signed in to change notification settings - Fork 31
/
memory.clj
44 lines (39 loc) · 1.5 KB
/
memory.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
(ns knossos.memory
"Helps manage memory pressure"
(:import (java.lang.management ManagementFactory
MemoryPoolMXBean
MemoryNotificationInfo
MemoryType)
(javax.management NotificationEmitter
NotificationListener
Notification)))
(def frac 0.9)
(defn on-low-mem!
"Invokes f when less than frac memory is free after GC. Globally mutates a
MemoryPoolMXBean. Returns a zero-arity function that, when called, cancels
the callback."
[f]
(let [^MemoryPoolMXBean pool
(->> (ManagementFactory/getMemoryPoolMXBeans)
(filter (fn [^MemoryPoolMXBean pool]
(and (= (.getType pool) MemoryType/HEAP)
(.isUsageThresholdSupported pool))))
last)]
; Set the collection usage threshold
(->> pool
.getUsage
.getMax
(* frac)
Math/floor
(.setCollectionUsageThreshold pool)))
; Hook up a listener
(let [^NotificationEmitter mem (ManagementFactory/getMemoryMXBean)
^NotificationListener l
(reify NotificationListener
(handleNotification [_ n hb]
(when (= (.getType n)
MemoryNotificationInfo/MEMORY_COLLECTION_THRESHOLD_EXCEEDED)
(f))))]
(.addNotificationListener mem l nil nil)
; Cancel callback
(fn cancel [] (.removeNotificationListener mem l))))