How to deal with Memory Leaks, that are caused by Binding

Hi, I recently noticed (huge?) memory leaks in my application and suspect bindings to be the cause of all the evil.
I made a little test case, which confirms my suspicion:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestAppMemoryLeak extends Application {
    public static void main(String[] args) {
        launch(args);
    @Override
    public void start(Stage stage) throws Exception {
        VBox root = new VBox();
        Button button = null;
        for (int i = 0; i < 100000; i++) {
            button = new Button();
            button.textProperty().bind(text);
            button.textProperty().unbind(); // if you don't call this, you can notice the increased memory of the java process.
        root.getChildren().add(button);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    private StringProperty text = new SimpleStringProperty("test");
}Now the problem is, HOW can I know, when a variable is no longer needed or overwritten by a new instance.
Just an example:
I have a ListView with a Cell Factory. In the updateItem method, I add a ContextMenu. The textProperty of each MenuItem is bound to a kind of global property, like in the example above. I have to do it in the updateItem method, since the ContextMenu differs depending on the item.
So every time the updateItem method is called a new ContextMenu is created, which binds some properties, but the old context menus remain in memory.
I guess there could be many more example.
How can I deal with it?

I've dealt with this situation and created a Jira issue for it, but I also have a work-around that is a bit unwieldy but works. I'll share it with you.
The bug that deals with this (in part atleast): http://javafx-jira.kenai.com/browse/RT-20616
The solution is to use weak invalidation listeners, however they are a bit of a pain to use as you cannot do it with something simplistic as "bindWeakly"... and you need to keep a reference around to the wrapped listener otherwise it will just get garbage collected immediately (as it is only weakly referenced). Some very odd bugs can surface if weak listeners disappear randomly because you forgot to reference them :)
Anyway, see this code below, it shows you some code that is called from a TreeCell's updateItem method (I've wrapped it in some more layers in my program, but it is essentially the same as an updateItem method):
public class EpisodeCell extends DuoLineCell implements MediaNodeCell {
  private final WeakBinder binder = new WeakBinder();
  @Override
  public void configureCell(MediaNode mediaNode) {
    MediaItem item = mediaNode.getMediaItem();
    StringBinding episodeRange = MapBindings.selectString(mediaNode.dataMapProperty(), Episode.class, "episodeRange");
    binder.unbindAll();
    binder.bind(titleProperty(), MapBindings.selectString(mediaNode.dataMapProperty(), Media.class, "title"));
    binder.bind(ratingProperty(), MapBindings.selectDouble(mediaNode.dataMapProperty(), Media.class, "rating").divide(10));
    binder.bind(extraInfoProperty(), Bindings.when(episodeRange.isNull()).then(new SimpleStringProperty("Special")).otherwise(episodeRange));
    binder.bind(viewedProperty(), item.viewedProperty());
    subtitleProperty().set("");
}This code makes use of a class called WeakBinder -- it is a helper class that can make Weak bindings and can keep track of them. When you call unbindAll() on it, all of the bindings it created before are released immediately (although they will also disappear when the Cell itself is garbage collected, which is possible because it only makes weak references).
I've tested this extensively and it solves the problem of Cells keeping references to objects with much longer life cycles (in my case, the MediaNode passed in has a longer lifecycle than the cells and so it is important to bind weakly to it). Before this would create huge memory leaks (crashing my program within a minute if you kept refreshing the Tree)... now it survives hours atleast and the Heap usage stays in a fixed range which means it is correctly able to collect all garbage).
The code for WeakBinder is below (you can consider it public domain, so use it as you see fit, or write your own):
package hs.mediasystem.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.property.Property;
import javafx.beans.value.ObservableValue;
public class WeakBinder {
  private final List<Object> hardRefs = new ArrayList<>();
  private final Map<ObservableValue<?>, WeakInvalidationListener> listeners = new HashMap<>();
  public void unbindAll() {
    for(ObservableValue<?> observableValue : listeners.keySet()) {
      observableValue.removeListener(listeners.get(observableValue));
    hardRefs.clear();
    listeners.clear();
  public <T> void bind(final Property<T> property, final ObservableValue<? extends T> dest) {
    InvalidationListener invalidationListener = new InvalidationListener() {
      @Override
      public void invalidated(Observable observable) {
        property.setValue(dest.getValue());
    WeakInvalidationListener weakInvalidationListener = new WeakInvalidationListener(invalidationListener);
    listeners.put(dest, weakInvalidationListener);
    dest.addListener(weakInvalidationListener);
    property.setValue(dest.getValue());
    hardRefs.add(dest);
    hardRefs.add(invalidationListener);
}Let me know if this solves your problem.

Similar Messages

  • What is the best way to deal with memory leak issue in sql server 2008 R2

    What is the best way to deal with memory leak issue in sql server 2008 R2.

    What is the best way to deal with memory leak issue in sql server 2008 R2.
    I have heard of memory leak in OS that too because of some external application or rouge drivers SQL server 2008 R2 if patched to latest SP and CU ( may be if required) does not leaks memory.
    Are you in opinion that since SQL is taking lot of memory and then not releasing it is a memory leak.If so this is not a memory leak but default behavior .You need to set proper value for max server memory in sp_configure to limit buffer pool usage.However
    sql can take more memory from outside buffer pool if linked server ,CLR,extended stored procs XML are heavily utilized
    Any specific issue you are facing
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • How to deal with the rule that do not use "object" class to declear a class

    I run my flex project in sonar. And there is a rule "Do not use Object class ".
    I just want to know how to deal with this problem.
    I mean, when I try to write a base class, I don't know which kind of class will be transfered in by reference, which type I can declear instead of "object"?

    Check out this example:
    The moment I put in the code >> box1.addItem("hello"); << and run the application, the BusNameListener is fired. Hope this makes sense.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class JFrameExample {
    private JComboBox box1;
    public JFrameExample() {
    box1 = new JComboBox();
    box1 .setMinimumSize(new Dimension(300, 24));
    box1 .setPreferredSize(new Dimension(300, 24));
    box1.addActionListener(new BusNameListener());
    box1.addItem("hello");
    JFrame f = new JFrame("This is a test");
    f.setSize(400, 150);
    Container content = f.getContentPane();
    // content.setBackground(Color.white);
    content.setLayout(new FlowLayout());
    content.add(box1);
    f.setVisible(true);
    class BusNameListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    String item = (String) cb.getSelectedItem();
    if (item != null) {
    JOptionPane.showInputDialog(null,
    "Specify...", "File Import",
    JOptionPane.OK_CANCEL_OPTION);
    }

  • How do I deal with Tokenized strings that are blank?

    I'm writing a little application that writes data to a file. It sends data to the file as a "|" delineated string. Then I use tokenizer to break up the string as follows:
    try {
                                  String searchtext = SearchTxt.getText();
                                  String tokenString = "";
                                  String[] returnData = new String[8];
                                  File filedata = new File("bigbase.txt");
                                  BufferedReader in = new BufferedReader(
                                  new FileReader(filedata));
                                  String line = in.readLine();
                                  while ( line != null) {
                                  Pattern pat = Pattern.compile(searchtext);
                                  Matcher mat = pat.matcher(line);
                                       if ( mat.find() ) {
                                       StringTokenizer t = new StringTokenizer(line, "|");
                                       maintextArea.setText("");
                                       int count = 0;
                                            while (t.hasMoreTokens()) {
                                                 tokenString = t.nextToken();
                                                 returnData[count] = tokenString;
                                                 maintextArea.append(tokenString + " ");
                                                 System.out.println(tokenString);
    etc etc etc
    The problem is that when the tokens are blank, I get an endless loop when I try to print out the data on that last line. How do I deal with Tokens that are blank so they don't endlessly loop my output?
    Thanks
    MrThis

    Most people would probably tell you to use:
    String.split(...);
    But I'm not most people and I wrote this class before regex support was added to the String class which is based on StringTokenizer but supports empty tokens:
    http://www.discoverteenergy.com/files/SimpleTokenizer.java

  • How to deal with Short dump that restarts the index server?

    Hi ,
    I have been experiencing this problem whenever any exception occurs in my SQL SCRIPT procedure. For instance when there is a situation when I try to insert a value of 50 characters in length to a column with max size of 40 it throws a short dump and restarts the index server. I tried to insert the exception handling code as well but still the problem persists. Is there a way to solve this issue?

    Hi Sudarshan
    crashes are rather generic reactions of the system to virtually any kind of problem that may occur.
    Memory shortage is one of the more common issues in current SAP HANA setups and SAP HANA development is heavily working on handling memory shortage situations more gracefully.
    Massive over allocation of memory, for example by very large intermediate result sets or join result sets typically can be addressed by correcting the query or model that leads to the issue.
    Anyhow, the initial post was not about a memory shortage but about a crash that seemed to have occurred with wrong data type handling.
    These are two very different kinds of problems, so I am not really sure how your comment relates here.
    - Lars

  • Organizational unit transfers ,how to deal with the person in it ?

    Hi,All,I need your help!
    if an organizational unit has been transfered to another upper organizational unit ,and there are already persons assigned to different positions of it,so how to deal with this problem?are those person's IT 0000,0001should be changed too?and how to maintain this kind of change?is a personnel action necessary?or there is some other more efficient way for it?

    Hi
    In IT0001 You have a Position which is linked to a Org unit. If you want to change the org units reporting relationship then you have to change it in OM by creating a new relationship with the upper org unit.
    All the person are assigned to position so nothing needs to be done in  PA.
    Reward points if useful.
    Regards

  • How to root out memory leak with  Java JNI & Native BDB 11g ?

    We are testing a web application using the 32-bit compiled native 11g version of BDB (with replication) under 32-bit IBM 1.5 JVM via JNI under 64-bit RedHat Linux. We are experiencing what appears to be a memory leak without a commensurate increase in Java heap size. Basically the process size continues to grow until the max 32-process size is reached (4Gb) and eventually stops running (no core). Java heap is set to 2Gb min/max. GCs are nominal, so the leak appears to be native and outside Java bytecode.
    We need to determine whether there is a memory leak in BDB, or the IBM JVM or simply a mis-use of BDB in the Java code. What tools/instrumentation/db statistic should be used to help get to root cause? Do you recommend using System Tap (with some particular text command script)? What DB stats should we capture to get to the bottom of this memory leak? What troubleshooting steps can you recommend?
    Thanks ahead of time.
    JE.
    Edited by: 787930 on Aug 12, 2010 5:42 PM

    That's troublesome... DB itself doesn't have stats that track VM in any useful way. I am not familiar with SystemTap but a quick look at it seems to imply that it's better for kernel monitoring than user space. It's pretty hard to get DB to leak significant amounts of memory. The reason is that it mostly uses shared memory carved from the environment. Also if you are neglecting to close or delete some object DB generally complains about it somewhere.
    I don't see how pmap would help if it's a heap leak but maybe I'm missing something.
    One way to rule DB out is to replace its internal memory allocation functions with your own that are instrumented to track how much VM has been allocated (and freed). This is very easy to do using the interfaces:
    db_env_set_func_malloc()
    db_env_set_func_free()
    These are global to your process and your functions will be used where DB would otherwise call malloc() and free(). How you get usage information out of the system is an exercise left to the reader :-) If it turns out DB is the culprit then there is more thinking to do to isolate the problem.
    Other ideas that can provide information if not actual smoking guns:
    -- accelerate reproduction of the problem by allocating nearly all of the VM to the JVM and the DB cache (or otherwise limit the allowable VM in your process)
    -- change the VM allocated to the JVM in various ways
    Regards,
    George

  • I am using an Macbook pro in conjunction with a Time Capsule. I back up all my aperture librarys on it, but how can i view these images that are stored on the capsule please ??

    I am using an Macbook pro in conjunction with a Time Capsule. I back up all my aperture librarys on it, but how can i view these images that are stored on the capsule please ??

    If you want to see what is in a file that is backed up by time machine then you have to restore the entire file. Having said that I have had good experience with Time Machine and individual files... if the file is there then all of it's components are almost for sure there. A way to get around this in Aperture would be to use referenced images. The images then still exist as individual files and can be backed up and restored individually. You would have to do so on a file by file basis though and your album information would still only be saved within the Aperture library.

  • I'm trying to find the plugin for camera raw, but all I can find is the page with the cameras that are supported. But I don't find how to find and install the actual plugin. The end name is ARW

    I'm trying to find the plugin for camera raw, but all I can find is the page with the cameras that are supported. But I don't find how to find and install the actual plugin. The end name is ARW, and all I need is to find WHERE I can download it. Thanks.

    cr is installed by updating your app.  use help>update, or update manually
    pre cc updates:  http://www.adobe.com/downloads/updates/
    cc updates:  http://prodesigntools.com/adobe-cc-updates-direct-links-windows.html
    cc 2104 updates:  http://prodesigntools.com/adobe-cc-2014-updates-links-windows.html

  • I have apps on my iPad and my computer is not connected to the Internet. How do I get my apps to load on the computer ? Because it says the apps on my iPad will be replaced with the apps that are on the computer but there is none there!

    I have apps on my iPad and my computer is not connected to the Internet. How do I get my apps to load on the computer ? Because it says the apps on my iPad will be replaced with the apps that are on the computer but there is none there!

    Authorize the computer in iTunes -- Store>Authorizie this computer.  Transfer the purchases from the iPad into iTunes and then you can sync with iTunes. Read this for instructions on transferring purchases from the iPad into iTunes.
    Transfer purchases.
    http://support.apple.com/kb/HT1848

  • When opening aperture I get Warning that says There was an error opening the database for the library "~/Desktop/Feb 12, 2011.aplibrary".  I'm concerned that my pictures may be lost.  Does anyone know how to deal with this Warning?

    When opening Aperture I get Warning that says "There was an error opening the database for the library “~/Desktop/Feb 12, 2011.aplibrary.”  That's it. The program does not open at all.  I'm concerned that my pictures may be lost.  Does anyone know how to deal with this Warning? 

    Might just need to rebuild the library...see this link:
    Aperture 3: Troubleshooting Basics

  • When I attempt to connect my new MacBook Air to my home network I receive a dialogue that says " Could not join name of network .  A connection timeout has occurred.  Any ideas on how to deal with this?

    When I attempt to connect my new MacBook Air to my home network I receive a dialogue that says " Could not join <name of network>.  A connection timeout has occurred.  Any ideas on how to deal with this?

    Please review the following Apple Support article for assistance with troubleshooting wireless connections.
    You may also find this OSXDaily article helpful as well.

  • How to deal with query that works like dir or ls

    I just can't figure it out how to deal with query that works like dir (Win32) or ls(unix) with special character like '*' and '?' , ex. c:\> dir j*.t?t
    Could somebody please tell me?

    Here's some code for using a FileFilter for the listFiles() method of the File class:
    import java.io.*;
        FileFilter myFileFilter = new MyFileFilter("*.t?t");
        File[] files = File.listFiles(myFileFilter);
      class MyFileFilter implements FileFilter {
            private String pattern;
            public MyFileFilter(String pattern) {
                this.pattern = pattern;
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return false;
                if (file.getName() ??matches?? pattern) {
                    // you'll have to put the pattern match code here!!
                    return true;
                return false;
      }maybe someone else can help with the pattern matching!

  • How can I share my ical work calendar with my coworkers that are using google calendar?

    How can I share my ical work calendar with my coworkers that are using google calendar?

    You can only do this by syncing your calendar to an external server - MobileMe is designed for this but if you don't already have a MobileMe account you can't start one now.
    If you do have a MobileMe account the method is described here:
    http://www.wilmut.webspace.virginmedia.com/notes/sharedcalendar.html#publicshare
    If you don't, you could sync to Google Calendar (Google accounts are free) or wait for iCloud which should be out in a couple of months and will probably provide this sort of facility.
    You might like to consider BusyCal which is like iCal Pro - similar to iCal but with extra facilities. It can sync calendars on a Lan and also between accounts on the same machine (you have to have fast user switching enabled).
    There is a free trial available on their website: it's slightly cheaper from the Mac App Store. (I have no connection with this company).

  • How to deal with this problem?

    How to deal with this problem?
    We plan to use Oracle Coherence (In Memory Data Grid) for a large-scale application. In order to keep the database table data in Coherence caches, we will create all the corresplonding Java objects (entities) and construct the persistence system using JPA/EclipseLink+JDBC. In this way, any in-memory object update will be persisted to the corresponding database tables.
    The problem is that some existing application codes are updating these database tables directly now. If the direct-database-table update is not permmited in the persistence environment, we have to discard most of the existing application scripts.
    I want to know, in this situation, should I discard most of the existing scripts?
    Are there any other solutions?

    Allowing writes from both cache & DB is possible with its own set of issues.
    The main issue to consider is conflicts from updates on same record via both cache and DB. If your caches are write-through the conflict decreases - but then cache writes become slower. If your caches are write-behind potentially the older cache update will overwrite the latest DB update. Now you are back to Database 101 -- timestamps, versions, etc...
    If you use a DB trigger to initiate the resync request you might want to distinguish whether the update has come from the cache-store (in which case, you may choose to do nothing), or if the update was from the 'existing apps', etc...
    If you choose to inject the resync logic at the application code level - you have the usual sourcecode issues - can you modify the code, is all the DB code localized, what options do you have to link with Coherence functionality (DLL, external proc, webservice, etc), etc... Naturally though, if you have to make substantial changes to signal a resync....you might consider taking the extra step and change the code to write to the cache.

Maybe you are looking for