What's the behavior of weak references to strings?...
# getting-started
c
What's the behavior of weak references to strings? (in all platforms) Since string constants are in the constant pool, does that mean a weak reference on them is never freed?
v
Just speaking about JVM, as you said, constants are in the constant pool. But not all strings are constants.
c
In theory, the JVM could still free a constant pool string when nothing uses it and reallocate it when a new value needs it, I wonder if it does that
m
Side-note: I was very surprised to see this kind of a question in #getting-started 😃 As for the answer, from what I can see in the JDK, the
intern
'd pool handles the strings via a
WeakReference
-like handle, which means -- once it's not strongly reachable -- it can be GC'd.
🧠 1
For a constant string literal, it is (almost always) strongly reachable via a constant pool, so @Vampire is correct 😃
😁 1
Technically, if you unload the class (with the constant pool) and then wait long enough, I guess it could be free'd, but this needs more investigation.
c
> Side-note: I was very surprised to see this kind of a question in #getting-started 😃 I know, but I didn't know where else to ask it 😅 #compiler doesn't really fit, it's definitely not #stdlib, etc
m
As for the
all platforms
part of the question, I have no idea from the top of my head, this also needs more digging in.
From what I see in Native, string literals are permanent globals and are never freed. I would not rely on this behavior as smth guaranteed by the Kotlin compiler; but I wouldn't expect it to reasonably change any time soon also 😃
c
Right. My use-case is that I have a function that parses
JSONPath
expressions. I have reasons to expect that users will create tons of those, and will create them inline (at usage site) instead of memoising them. I'm considering adding an automatic cache, but since they will almost always be in the constant pool I was wondering whether a WeakMap would make sense at all in this situation.
Since the memory is never (or very rarely) cleared, I guess the answer is "that's going to be a lot of memory usage so it's probably not a good idea by default"
m
I guess a good ol' LRU cache or simply a FIFO one should work for a lot of workloads?