-1

Memory allocated to string buffer is not getting cleared even we did

stringbuffer.delete(0,Stringbuffer.length());
stringbuffer = null;
System.gc();

Any suggestion to remove entire memory allocated to string buffer.

Taher Ahmed Ghaleb
  • 4,558
  • 5
  • 25
  • 37
  • 2
    When gc runs it will clear memory is there are no references to it. How do you know that the memory is not being cleared? – puhlen Dec 04 '18 at 06:22
  • Possible duplicate of [When does System.gc() do anything](https://stackoverflow.com/questions/66540/when-does-system-gc-do-anything) – LuCio Dec 04 '18 at 07:27
  • Remove from what? Is it supposed to punch a hole into your RAM chips? The garbage collector will make the RAM *available* to other objects, not modify it. As long as no-one reuses the memory for other purposes, it may keep its old contents. That also applies to other programming languages with manual memory deallocation. – Holger Dec 04 '18 at 08:55
  • StringBuilder.delete() doesn't free any memory. Not using the stringBuilder anywhere makes it available for clean up. BTW Please don't use StringBuffer if you can as it was replaced by StringBuilder more than ten years ago. – Peter Lawrey Dec 06 '18 at 09:18
  • _"Memory allocated to string buffer is not getting cleared"_ How do you know? – Mark Rotteveel Dec 06 '18 at 15:18

1 Answers1

1

You cannot control Java memory management. Even by calling System.gc(). By calling System.gc() you can only suggest JVM to collect garbage but cannot force to free memory Java will collect garbage memory based on its algorithm only

System.gc() javadoc says

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Source :-System.gc()

Tarun
  • 944
  • 6
  • 17