Igor
Igor

Reputation: 566

After Text was deleted from JTextArea, heap is not empty

I have an application with AWT GUI, and I use JTextArea for logging output. If I erase the text with setText(null) or removeAll() or setText("") and then run garbage collector System.gc(), I notice that the whole text still in memory. How can I really delete the text?

I'm not very familiar with profiler, here is what I see in memory dump after setText(null):

profiler snapshot

Upvotes: 0

Views: 408

Answers (3)

trashgod
trashgod

Reputation: 205785

As @DavidK notes System.gc() is not a useful way to examine this. Using the mechanism described here, most profilers can force garbage collection in a way that, subject to some limitations, is a useful debugging tool.

Upvotes: 4

David Kroukamp
David Kroukamp

Reputation: 36423

Please have a read on: How Garbage Collection works in Java.

As per the docs System.gc():

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

NB - suggests. This means that the garbage collector is only suggested to do a clean up and not forced also it may entirely ignore your request, thus we cannot know when the garbage will be collected only that it will be in time.

NB - disgarded objects: this refers to all objects that are not static/final or in use/referenced by any other instances/classes/fields/variables etc.

Here is also an interesting question I found on the topic:

with the top answer going along the lines of:

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken

and further there has even been a bug submitted for the bad phrasing of the documentation:

.

Upvotes: 4

Subba
Subba

Reputation: 406

  1. if there are any String objects holding this content in your client program, please set them to null as well.

  2. Also you don't need to explicitly call the System.gc() mothod. JVM does garbage collects the orphaned objects when ever it needs more memory to allocate for other objects.

  3. you only need to worry about if you a see an out of memory / continuous heap memory increase usage etc.

Upvotes: 2

Related Questions