Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6507038: Memory Leak in JTree / BasicTreeUI #17458

Closed
wants to merge 10 commits into from

Conversation

prsadhuk
Copy link
Contributor

@prsadhuk prsadhuk commented Jan 17, 2024

When using a TreeCellRenterer which creates new components in getTreeCellRendererComponent() in a JTree that is not visible, changes to the nodes cause a memory leak.
When a node is changed, the Method getNodeDimensions() is called to calculate the new dimensions for the node. In this method, getTreeCellRendererComponent() is called to obtain the renderer component (what else...) and this component is added to rendererPane. It is not removed from the rendererPane afterwards.
Only when the tree is painted, the paint() method does a removeAll on the rendererPane in this code

FIx is added to remove the components from rendererPane when the JTree UI is changed/uninstalled only when tree is not visible since they are already removed when tree is painted in paint() method..


Progress

  • Change must be properly reviewed (1 review required, with at least 1 Reviewer)
  • Change must not contain extraneous whitespace
  • Commit message must refer to an issue

Issue

  • JDK-6507038: Memory Leak in JTree / BasicTreeUI (Bug - P4)

Reviewers

Contributors

  • Alexey Ivanov <aivanov@openjdk.org>

Reviewing

Using git

Checkout this PR locally:
$ git fetch https://git.openjdk.org/jdk.git pull/17458/head:pull/17458
$ git checkout pull/17458

Update a local copy of the PR:
$ git checkout pull/17458
$ git pull https://git.openjdk.org/jdk.git pull/17458/head

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 17458

View PR using the GUI difftool:
$ git pr show -t 17458

Using diff file

Download this PR as a diff file:
https://git.openjdk.org/jdk/pull/17458.diff

Webrev

Link to Webrev Comment

@bridgekeeper
Copy link

bridgekeeper bot commented Jan 17, 2024

👋 Welcome back psadhukhan! A progress list of the required criteria for merging this PR into master will be added to the body of your pull request. There are additional pull request commands available for use with this pull request.

@openjdk openjdk bot added the rfr Pull request is ready for review label Jan 17, 2024
@openjdk
Copy link

openjdk bot commented Jan 17, 2024

@prsadhuk The following label will be automatically applied to this pull request:

  • client

When this pull request is ready to be reviewed, an "RFR" email will be sent to the corresponding mailing list. If you would like to change these labels, use the /label pull request command.

@openjdk openjdk bot added the client client-libs-dev@openjdk.org label Jan 17, 2024
@mlbridge
Copy link

mlbridge bot commented Jan 17, 2024

Copy link
Contributor

@honkar-jdk honkar-jdk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran the reproducer attached to JBS without and with the fix. The "Live Label count" seem to increase in both cases.
After running the test, I switched to tab 2, which makes tab 1 (with JTree) inactive but during this time the Live label count increases.
Will a test case be added as part of this fix?

Live TestLabels:0
Live TestLabels:74
Live TestLabels:57
Live TestLabels:21
Live TestLabels:60
Live TestLabels:46
Live TestLabels:62
Live TestLabels:102
Live TestLabels:140
Live TestLabels:180
Live TestLabels:218
Live TestLabels:256
Live TestLabels:296
Live TestLabels:334
Live TestLabels:374
Live TestLabels:412
Live TestLabels:452
Live TestLabels:490

@prsadhuk
Copy link
Contributor Author

As mentioned in the comment

// Only ever removed when UI changes, this is OK!
rendererPane.add(aComponent);

the components are to be removed when UI changes, so I guess it is expected to increase if UI is not changing (ie. in case tree is not visible) so I have removed at end when component is uninstalled at which point it is a leak too, if not removed..
A testcase is hard to provide for this leak..it's all notional..

@mrserb
Copy link
Member

mrserb commented Jan 19, 2024

can we trigger this memory leak by some new or existed tests?

@prsadhuk
Copy link
Contributor Author

I cant see any nor can I think of any..you have any idea?

@@ -1334,6 +1334,9 @@ protected void uninstallKeyboardActions() {
*/
protected void uninstallComponents() {
if(rendererPane != null) {
if (!tree.isVisible()) {
rendererPane.removeAll();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if( -> if (

Is it actually necessary to check visibility ?

But more importantly, in the case of the test in the bug, how and when does this uninstallComponents() method get called ? It isn't clear to me how it changes the reported behaviour of that test.

I thought uninstallComponents() is just part of uninstallUI() like when tearing down and freeing the tree, or at least switching L&F .. whereas the submitter seems to be implying nodeChanged() is the problem

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the submitter mentioned during nodeChanged() but I mentioned it before in this comment
that the comment present, implied it's not an issue, if the component is not removed if UI is not changed (as it is in the case when tree is not visible)...I am not sure why it was added and when but should we ignore that comment and try to remove the component even if tree is not visible (and UI is not changing)?

I went with the thought that the coder meant what he said and I freed the components at the end (as you told during tearing down) so that there is no leak..

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My point is not about whether this is the only case we need to address, I am asking what harm could come from removing the isVisible() test here ?

Comment on lines 1337 to 1338
if (!tree.isVisible()) {
rendererPane.removeAll();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be enough to remove rendererPane from and assign null to it?

It's done this way in BasicTableUI and BasicListUI:

table.remove(rendererPane);
rendererPane = null;
table = null;

and
list.remove(rendererPane);
rendererPane = null;
list = null;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is already been done in completeUIUninstall called from uninstallUI
rendererPane.removeAll is done to remove all components that are added in getNodeDImensions which gets removed in paint but if tree is not visible, then paint is not called so those components are not removed, which I am trying to do now in uninstallUI by checking tree visibility condition

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I see it. Then the added lines in uninstallComponents aren't needed because rendererPane is assigned null in completeUIUninstall which is called right after uninstallComponents, therefore rendererPane itself and all the components added into it are eligible for garbage collection.

Where is the memory leak then?

@aivanov-jdk
Copy link
Member

can we trigger this memory leak by some new or existed tests?

I cant see any nor can I think of any..you have any idea?

As far as I understand, the renderer component is leaked.

Usually, the renderer isn't re-created each time getTreeCellRendererComponent() is called. So, we can create a renderer component and store a weak/phantom reference to it.

After tree.uninstallUI is called, the renderer component should be freed. You can use ForceGC class for it. A sample usage of ForceGC can be found in AwtListGarbageCollectionTest.java or other tests.

@aivanov-jdk
Copy link
Member

As mentioned in the comment

// Only ever removed when UI changes, this is OK!
rendererPane.add(aComponent);

the components are to be removed when UI changes, so I guess it is expected to increase if UI is not changing (ie. in case tree is not visible) so I have removed at end when component is uninstalled at which point it is a leak too, if not removed..
A testcase is hard to provide for this leak..it's all notional..

This is an interesting part… If the renderer component is added over and over again into rendererPane this creates a leak, especially if currentCellRenderer.getTreeCellRendererComponent returns a new component each time it's called.

To me, rendererPane should contain only one component — the one that's returned by appropriate cell renderer and that is currently used for painting, measuring etc.

@prrace
Copy link
Contributor

prrace commented Jan 23, 2024

I am not sure what "notional" means - do you mean there is no actual leak ?
If there's no actual leak we don't need a fix.
If we have just one component that is sitting in a list owned by renderPane that's not much of a "leak".
I am not sure this is worth "fixing".

But if somehow - as discussed above repeated calls to renderPane.add(Component) accumulate components
when there should only ever be one, what would that mean in a program which then DOES display the tree
after adding (eg) 5 components ?

If having 5 makes no sense, can we (should we ?) stop more than one from being added ?
I think that may also be Alexei's point.

@openjdk openjdk bot removed the rfr Pull request is ready for review label Jan 24, 2024
@openjdk openjdk bot added the rfr Pull request is ready for review label Jan 24, 2024
@prsadhuk
Copy link
Contributor Author

Yes, seems like rendererPane should retain the last rendering component..No regression is observed in SwingSet2 or in other tree tests..
Updated PR to stop more than one component being added.
Testcase added too..

smCount++;
}

public void finalize( ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The finalize method is deprecated. Can't we use Reference API for this purpose?

Store a list of PhantomReference<JLabel>. The size of the list is the number of JLabel objects created. Once you receive a reference via the ReferenceQueue, remove it from the list.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was not sure of the nuances of PhantomReference and ReferenceQueue, so have used WeakReference logic in the test which I think is more simpler..

Copy link
Member

@aivanov-jdk aivanov-jdk Jan 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's simpler with PhantomReference. This type of reference does not allow getting its referent, and it's not needed in this case. When the referent of a reference is cleared by the GC, the reference is added into the associated reference queue. This is true for any type of Reference, but PhantomReference has to use a reference queue.

Here's how to use them: aivanov-jdk@b0da8b3

I keep the references in a list. The size of the list is the number of live JLabel objects. On each iteration, I poll the reference queue and remove the dead references from the list.

synchronized (referenceList) {
start = referenceList.size();
Reference<?> ref;
while ((ref = referenceQueue.poll()) != null) {
referenceList.remove(ref);
removed++;
}
left = referenceList.size();
}

If the number of removed references is zero, the test fails because objects are leaked. Otherwise, the test passes. This aligns with your latest changes.

Your code also does the job. I'll approve it if you don't want to use PhantomReference.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your "reference" on PhantomReference..Although my testcode is doing same thing (which you acknowledged) no harm in trying new way (for me) for my future reference so have updated the test to use PhantomReference.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add me as contributor, please?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It didn't work. It would've, if you'd added a blank between the two line.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let me retry

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/contributor add @aivanov-jdk

Copy link
Member

@aivanov-jdk aivanov-jdk Feb 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like it needs to be a top-level comment rather than a reply to code change discussion.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm...it is a comment..should be parsed accordingly, I presumed...let me retry..

label.setBackground(getBackgroundNonSelectionColor());
}

weakRefArrLabel.add(smCount++, new WeakReference<JLabel>(label));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
weakRefArrLabel.add(smCount++, new WeakReference<JLabel>(label));
synchronized (weakRefArrLabel) {
weakRefArrLabel.add(new WeakReference<JLabel>(label));
}

You have to add items in a synchronized block; you read from the list in another thread. (Reading has be done inside a synchronized block too.)

Just add to the end of the list.

Comment on lines 156 to 164
SwingUtilities.invokeAndWait(new Runnable( ) {
public void run( ) {
DefaultTreeModel model = (DefaultTreeModel) jTree1.getModel();
TreeNode root = (TreeNode) model.getRoot();
DefaultMutableTreeNode n = (DefaultMutableTreeNode) model.getChild(root, 0);
n.setUserObject("runcount " + currentCount);
model.nodeChanged(n);
}
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The anonymous class can be a lambda expression.

The code inside the Runnable can be reduced to

n.setUserObject("runcount " + currentCount);
model.nodeChanged(n);

This implies, you make n a field and initialise it in initComponents; or after calling initComponents.

Comment on lines 200 to 204
for (WeakReference<JLabel> ref : weakRefArrLabel) {
if (ref.get() == null) {
count++;
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have to iterate over weakRefArrLabel in a synchronized block. (No, declaring weakRefArrLabel as volatile is not enough.)

Suggested change
for (WeakReference<JLabel> ref : weakRefArrLabel) {
if (ref.get() == null) {
count++;
}
}
synchronized (weakRefArrLabel) {
for (WeakReference<JLabel> ref : weakRefArrLabel) {
if (ref.get() == null) {
count++;
}
}
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, you can use Stream API:

    private long getCleanedUpLabelCount() {
        synchronized (weakRefArrLabel) {
            return weakRefArrLabel.stream()
                                  .filter(r -> r.get() != null)
                                  .count();
        }
    }

Comment on lines 3283 to 3284
rendererPane.removeAll();
// Only ever removed when UI changes, this is OK!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment no longer applies—you remove all the components from rendererPane on the line above.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only important thing that prevents me from approving this PR. The comment is misleading now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, modified

Comment on lines +3283 to +3285
// Remove previously added components to prevent leak
// and add the current component returned by cellrenderer for
// painting and other measurements
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the comment is redundant.

@openjdk
Copy link

openjdk bot commented Feb 1, 2024

@prsadhuk This change now passes all automated pre-integration checks.

ℹ️ This project also has non-automated pre-integration requirements. Please see the file CONTRIBUTING.md for details.

After integration, the commit message for the final commit will be:

6507038: Memory Leak in JTree / BasicTreeUI

Co-authored-by: Alexey Ivanov <aivanov@openjdk.org>
Reviewed-by: honkar, aivanov

You can use pull request commands such as /summary, /contributor and /issue to adjust it as needed.

At the time when this comment was updated there had been 451 new commits pushed to the master branch:

  • 3d3a8f0: 8325432: enhance assert message "relocation addr must be in this section"
  • b58d73b: 8323746: Add PathElement hashCode and equals
  • 917838e: 8325150: (tz) Update Timezone Data to 2024a
  • 43089bf: 8325399: Add tests for virtual threads doing Selector operations
  • d109903: 8325028: (ch) Pipe channels should lazily set socket to non-blocking mode on first use by virtual thread
  • 1fb9e3d: 8325304: Several classes in java.util.jar and java.util.zip don't specify the behaviour for null arguments
  • 9cccf05: 8325367: Rename nsk_list.h
  • be7cc1c: 8323681: SA PointerFinder code should support G1
  • fbd15b2: 8325189: Enable this-escape javac warning in java.base
  • 299a8ee: 8325302: Files.move(REPLACE_EXISTING) throws NoSuchFileException on deleted target
  • ... and 441 more: https://git.openjdk.org/jdk/compare/dd517c64047705d706b095d15d9fd4e0703ab39b...master

As there are no conflicts, your changes will automatically be rebased on top of these commits when integrating. If you prefer to avoid this automatic rebasing, please check the documentation for the /integrate command for further details.

➡️ To integrate this PR with the above commit message to the master branch, type /integrate in a new comment.

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Feb 1, 2024
@prsadhuk
Copy link
Contributor Author

prsadhuk commented Feb 2, 2024

/contributor add @aivanov-jdk

@openjdk
Copy link

openjdk bot commented Feb 2, 2024

@prsadhuk
Contributor Alexey Ivanov <aivanov@openjdk.org> successfully added.

Comment on lines 112 to 117
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
jPanel2 = new javax.swing.JPanel();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fully qualified class name are redundant here since we already have the required imports.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

Comment on lines +24 to +30
/*
* @test
* @bug 6507038
* @key headful
* @summary Verifies memory leak in BasicTreeUI TreeCellRenderer
* @run main TreeCellRendererLeakTest
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jtreg header can be moved to before class declaration location.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No consensus on it yet so kept it same..

Copy link
Contributor

@honkar-jdk honkar-jdk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good apart from the minor formatting issues mentioned above.
The updated test works well with the fix.

@prsadhuk
Copy link
Contributor Author

prsadhuk commented Feb 8, 2024

/integrate

@openjdk
Copy link

openjdk bot commented Feb 8, 2024

Going to push as commit e8ceb71.
Since your change was applied there have been 451 commits pushed to the master branch:

  • 3d3a8f0: 8325432: enhance assert message "relocation addr must be in this section"
  • b58d73b: 8323746: Add PathElement hashCode and equals
  • 917838e: 8325150: (tz) Update Timezone Data to 2024a
  • 43089bf: 8325399: Add tests for virtual threads doing Selector operations
  • d109903: 8325028: (ch) Pipe channels should lazily set socket to non-blocking mode on first use by virtual thread
  • 1fb9e3d: 8325304: Several classes in java.util.jar and java.util.zip don't specify the behaviour for null arguments
  • 9cccf05: 8325367: Rename nsk_list.h
  • be7cc1c: 8323681: SA PointerFinder code should support G1
  • fbd15b2: 8325189: Enable this-escape javac warning in java.base
  • 299a8ee: 8325302: Files.move(REPLACE_EXISTING) throws NoSuchFileException on deleted target
  • ... and 441 more: https://git.openjdk.org/jdk/compare/dd517c64047705d706b095d15d9fd4e0703ab39b...master

Your commit was automatically rebased without conflicts.

@openjdk openjdk bot added the integrated Pull request has been integrated label Feb 8, 2024
@openjdk openjdk bot closed this Feb 8, 2024
@openjdk openjdk bot removed ready Pull request is ready to be integrated rfr Pull request is ready for review labels Feb 8, 2024
@openjdk
Copy link

openjdk bot commented Feb 8, 2024

@prsadhuk Pushed as commit e8ceb71.

💡 You may see a message that your pull request was closed with unmerged commits. This can be safely ignored.

@prsadhuk prsadhuk deleted the JDK-6507038 branch February 8, 2024 11:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client client-libs-dev@openjdk.org integrated Pull request has been integrated
6 participants