Search code examples
javaswingheap-memoryjtextareaprofiler

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


Solution

  • 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:

    .