Regarding Java String Constant Pool

2019-01-26 08:39发布

问题:

This is regarding the Java String Constant Pool. In one of my Programs i am decrypting the password for the database and storing it in a String. I heard that the Java Strings will be stored in a Constant pool and they won't be destroyed the VM restarts or the ClassLoader that loaded the String Quits.

If it is the case my passwords will be stored in the String pool. I am Very concerned about this issue. Is there any other way to destroy these literals or anything else i can do.

Please suggest on this,

Regards, Sunny.

回答1:

There are several different issues at play here. First, the term "constant pool" refers to a very specific part of class files for string and numerical literals, or to the data structures generated from this part of class files that reside in the JVM. Password won't be stored here unless they're part of class files.

However, some String objects are indeed stored and shared throughout the program through String internment. Any string literal is automatically interned, as are any strings that you invoke the intern() method on. To the best of my knowledge, though, no other strings are stored this way, so unless you automatically intern the strings holding passwords yourself I don't think you need to worry about this.

One other issue to be aware of is that if you don't want the passwords residing in memory, you may need to be careful about garbage collection since a String that is no longer referenced could still be in memory. Similarly, if you use certain string methods like substring that share backing representations between strings, you may keep around the full password string after you're done using it.

If what you're worried about is other Java code being able to see old passwords that have been interned or that still live in memory, though, you don't need to worry. There is no way to iterate or look at the elements of the interned string pool, or to crack open a String to see its backing array.



回答2:

This only applies to String literals and Strings that you have called the intern() method on. Think about it: if it applied to all strings then you would quickly run out of memory in e.g. a servlet application that handles request parameters with different (String) values.



回答3:

Dude, use a string buffer for getting the password and doing your (presumably) string-type operations on.

StringBuffer stores strings as char[], which can be deleted. Or overridden or what have you. Say StringBuffer.delete(0,StringBuffer.length());

Or just get the db password as a char[] and work directly on that - but i think the StringBuffer way (assuming you've made all your code using String methods) will be an easier leap.