How can I ensure the destruction of a String object in Java?

So, here’s the bad news. i’m surprised no one has mentioned it yet. with modern garbage collectors, even the whole char[] concept is broken. regardless of whether you use a String or a char[], the data can end up living in memory for who-knows-how-long. why is that? because modern jvms use generational garbage collectors which, in short, copy objects all over the place. so, even if you use a char[], the actual memory it uses could get copied to various locations in the heap, leaving copies of the password everywhere it goes (and no performant gc is going to zero out old memory). so, when you zero out the instance you have at the end, you are only zeroing out the latest version in memory.

long story, short, there’s no bulletproof way to handle it. you pretty much have to trust the person.

Leave a Comment