Does string constant pool works with singleton annotated variables too?

Viewed 126
object Keys {
    @Singleton
    const val KEY_Q = "question"
    @Singleton
    const val KEY_ID = "quesid"
}

I am using Singleton annotation with many string variables in my singleton class. I wanted to ask as by default a string variable is stored in the constant string pool, and during the updating process, JVM checks in the string pool if the same variable is available or not, if yes then it returns the reference of the same without creating a new one.

as we can see in the picture

Now I want to ask, does this process works the same when we are using singleton annotation with our string variables. If yes then is there any benefit for me to use such a class with these annotations with different variables. I am a newbie to singletons please describe in detail. Thanks

1 Answers

Annotations make no difference to string pool behavior in Java. If your example was Java, the @Singleton annotations would not save memory1.

There is a very simple rule that covers what goes into the string pool in Java.

  • If a string is a result of evaluating a compile time constant expression then a single copy is placed in the string pool. The JLS specifies what a compile time constant expression is2.

  • The only other circumstance in which a string goes into the string pool3 is if some code explicitly calls intern on it.

However ...

In a modern JVM on modern hardware, it is most likely to be irrelevant whether a string goes into the string pool.

  • The string pool is part of the heap and is garbage collected like the rest of the heap.

  • The space taken by each individual string literal is most likely to be trivial compared to the rest of your application's memory usage. A few bytes, compared with megabytes ... or gigabytes.

  • If you think you can intern strings and exploit the special property of strings in the string pool (by using == to compare strings) you are treading on very dangerous grounds. This is a micro-optimization ... and it only works if you can be sure that you have interned all of the strings. (And besides, interning is more expensive that a few string comparisons, so your attempt at optimizing might be a failure.)

  • Finally, since Java 9, the GC performs automatic string de-duping for strings that have survived a few GC cycles. So if you really do have a lot of string data with a lot of duplicates, the best solution is to let the GC handle it.


1 - I cannot tell you exactly what this means for your example, because you are using syntax that is not valid Java. Java doesn't have a const, val or object keywords. This looks like Kotlin.
2 - Common examples are a string literal or a concatenation of string literals, but there are others; see JLS 15.28.
3 - It is implementation dependent whether the string itself or a copy of the string goes into the pool. But it is really difficult for an application to distinguish the different behaviors.

Related