What is the fastest way to release memory of stringbuilder .
StringBUilder sb = new StringBuilder();
sb.apppend(maximum value possible);
Below are the code snippets which i tried to release memory as fast as possible and make the object eligible for garbage collection
Option 1:
sb = null;
As per my understanding all the data in the stringbuilder will be deleted and object will be eligible for garbage collection as soon as it is kicked in, but the memory of the text which is occupied by stringbuilder will be released. Also will the string value in it also be deleted from heap or will be stored in string pool ?
Option 2:
sb.setLength(0);
This will reset the lenght of string builder but it will not be garbage collected
Option 3:
sb.delete(0,sb.length());
This will reset the string builder by deleting all the data in it but it will not be garbage collected
Option 4:
sb.delete(0,sb.length());
sb = null;
This will reset the string builder and also make it eligible for garbage collection?!
If you really want the memory to be released as fast as possible, then GC options are where you need to look, not code.
A detailed analysis of GC options for this purpose is beyond what can sensibly fit here - but specifically, the new Shenandoah GC can be tuned to be much more aggressive at releasing memory than G1 or concurrent mark/sweep, so this is probably what you'd want to use. You can specify this with -XX:+UseShenandoahGC
. (It's OpenJDK specific and experimental at this point, but if you want the behaviour you're after, it's the one to go for.)
For fast release times, you would want to use a small value for ShenandoahUncommitDelay
and ShenandoahGuaranteedGCInterval
. Smaller values here (broadly speaking) will run the GC more often and more aggressively, therefore using more CPU cycles - but it will have the effect that you're after, that memory will be released incredibly quickly in comparison to previous GC incarnations.
If you just want to make sure that the memory is released so it's eligible for garbage collection quickly, then you just need to make sure all references to that StringBuilder
are set to null at the soonest opportunity. Even in this case though, I'd encourage you to profile and check if you need to do this explicitly - in many cases now, the JVM is smart enough to mark objects as eligible for GC even if they're technically still in scope (so long as it can see they're no longer referenced for the remainder of that scope.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With