Will a string passed from outside of a Java application be stored in a string pool?

I read many answers but none of them answered my question.

If I have a java service running on some port and the client connects to it and calls a method like:

String data = getServiceData("clientKey");

      

Now my question is, will this key (clientKey) be stored in a string literal pool from the service side? Generally, literals that should be stored in persistent pools are evaluated at compile time, but what happens to strings that are passed from outside the JVM, or might be when reading a file?

+3


source to share


2 answers


Most methods that read strings from external sources (especially BufferedReader.getLine()

or Java serialization) will not intern strings, so there will be no response.

However, if you use third-party libraries, they can do this: for example, there are some XML / Dom parsers known to do this (at least for element names, less commonly for values). Also some high performance frameworks (servlet containers) for them for specific strings (like HTTP header names).

But it is usually used very rarely in good (!) Implementations, since it is much less desirable than one might think. Don't forget: before you can put a string, it must exist as an object that needs to be collected anyway, so in terms of avoiding garbage with help intern()

doesn't help. This can only reduce the memory of the working set if these strings survive for a long time (which is not in OLTP) and can speed up the consistency check a little. But it usually only helps if you are doing thousands of them on the same string object.

You can check yourself if the string is already interned (you should of course not do this in production code as it puts your string and may not work in all implementations):



input == input.intern()?"yes":"no"`

      

And yes (as pointed out in the comment), a million instances of the same API key can happen to this. But don't be fooled into thinking this is bad. In fact, interning them would have to look for value and deal with a growing pool of strings. This may take longer than processing (and freeing) the row. Especially when the JVM can optimize the distribution of rows in distribution analysis and generational analysis.

BTW: Java 8u20 has a ( -XX:+UseStringDeduplication -XX:+PrintStringDeduplicationStatistics

) function to detect duplicate lines in the background while doing garbage collection in G1. It will concatenate these string arrays to reduce memory consumption. ( JEP192 )

+2


source


The String object is serialized on your client side and deserialized and stored in heap memory. If you want it to be stored in your string pool memory, you must use the intern () method .



    String value;
    String data = (value =getServiceData("clientKey"))==null?null:value.intern();

      

+3


source







All Articles