Memory leak with File Write.vi

Hi All,
I am trying to save a big data cluster, which includes images, into a data log file. The vis I use are: New File.vi, Write File.vi, Close File.vi.
The problem is Write File.vi has memory leak  when the data cluster includes images .
Anyone sees similar case?  Any solution?
Thanks.
Aiqiu

Aiqiu,
I am glad you found out about flattening your image to a string.  I was about to post and say that you probably didn't want to save the IMAQ image reference to a file, because after you closed the image in memory, there wouldn't be anything for the IMAQ image reference to point to.  You are correct to flatten the image to a string.  Below is a link to a document which discusses doing this to communicate over datasocket, but the processes of flattening the image to a string is the same regardless of whether or not you are sending the image across a datasocket connection or saving to a file.
Transfering Images with DataSocket
As for the memory leak.  I am pretty sure that if you passed all of the IMAQ Image references created in the "Image Init Buffer.vi" subVI and then closed each reference individually, that the memory leak would probably go away.
Lorne Hengst
Application Engineer
National Instruments

Similar Messages

  • Memory leak with UI automation

    Hi, 
    I noticed there is memory leak with UI automation in my window 8.1.
    I noticed there is solution for window 8
    http://support.microsoft.com/kb/2885482
    Is there any solution for window 8.1?
    I really appreciate for any help.

    Hi,
    I'm sorry for didn't hear anything about this issue. I'll try to connect the writer of this KB, hope we can find some suggestion. If there is any progress about this problem, I would come back.
    Roger Lu
    TechNet Community Support

  • Memory Leak with JPopupMenu

    It seems there is a memory leak with JPopupMenu. The following program demonstrates this leak. If you run the program, click on show form, and then close the form, the used memory will be GCd appropriately. If you click on show form, then right click on the table to show the popup (even if you dont do anything else with the popup) then close the form, it never GCs the form. I've tried all kinds of crazy things, but I cant seem to find what is keeping the memory from being GCd.
    Peter
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    @SuppressWarnings("serial")
    public class TriState extends JPanel {
         private static final long               K               = 1024;
         private static final long               M               = K * K;
         private static final long               G               = M * K;
         private static final long               T               = G * K;
         protected static int ctr = 1;
         private JButton                              btnShow          = new JButton("Show Form");
         private JLabel                              lblMem          = new JLabel();
         private static final DecimalFormat     df               = new DecimalFormat("#,##0.#");
         protected Timer                              updateTimer     = new Timer();
         public TriState() {
              this.setLayout(new GridLayout());
              add(btnShow);
              add(lblMem);
              updateTimer.scheduleAtFixedRate(new UpdateTimerTask(), 1000, 1000);
              btnShow.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        FrmReferrals fr = new FrmReferrals();
                        fr.setVisible(true);
         class UpdateTimerTask extends TimerTask {
              public void run() {
                   SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                             dumpMemoryUsage();
         protected void dumpMemoryUsage() {
              System.gc();
              Long t = Runtime.getRuntime().totalMemory();
              long f = Runtime.getRuntime().freeMemory();
              String st = convertToStringRepresentation(t);
              String sf = convertToStringRepresentation(f);
              String su = convertToStringRepresentation(t - f);
              System.out.println("Total:" + st + "(" + t + ") Free:" + sf + "(" + f + ") Used:" + su + "(" + (t - f) + ")");
              lblMem.setText(su + "/" + st);
         public static String convertToStringRepresentation(final long value) {
              final long[] dividers = new long[]{T, G, M, K, 1};
              final String[] units = new String[]{"TB", "GB", "MB", "KB", "B"};
              if (value < 1)
                   throw new IllegalArgumentException("Invalid file size: " + value);
              String result = null;
              for (int i = 0; i < dividers.length; i++) {
                   final long divider = dividers;
                   if (value >= divider) {
                        final double dr = divider > 1 ? (double) value / (double) divider : (double) value;
                        result = df.format(dr) + units[i];
                        break;
              return result;
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SimpleTableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TriState newContentPane = new TriState();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         protected class PopupMenu extends JPopupMenu {
              public PopupMenu() {
                   JRadioButtonMenuItem item1 = new JRadioButtonMenuItem(new AbstractAction("Insert Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item1.setActionCommand("Insert");
                   add(item1);
                   JRadioButtonMenuItem item2 = new JRadioButtonMenuItem(new AbstractAction("Delete Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item2.setActionCommand("Delete");
                   add(item2);
         public class FrmReferrals extends JFrame {
              public FrmReferrals() {
                   super();
                   init();
              protected void init() {
                   jbInit();
              protected void closeIt() {
                   uninit();
              // variables here
              protected Dimension          dimPreferred     = new Dimension(1270, 995);
              protected JTabbedPane     tabbedPane          = new JTabbedPane();
              protected JTable          tblReferrals     = null;
              protected PopupMenu          popMenu           = new PopupMenu();
              protected void jbInit() {
                   setPreferredSize(dimPreferred);
                   setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   setTitle("Referrals");
                   JPanel pnl = new JPanel();
                   pnl.setOpaque(false);
                   pnl.setLayout(new BorderLayout());
                   pnl.add(tabbedPane, BorderLayout.CENTER);
                   // put it all in the frame
                   add(pnl);
                   pack();
                   setLocationRelativeTo(null);
                   // init the table and model
                   ReferralsTableModel ctm = new ReferralsTableModel(buildDummyVector());
                   tblReferrals = new JTable(ctm);
                   tblReferrals.setComponentPopupMenu(popMenu);
                   tblReferrals.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                   tabbedPane.add(new JScrollPane(tblReferrals, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
                   addWindowListener(new WindowListener() {
                        @Override
                        public void windowActivated(WindowEvent e) {}
                        @Override
                        public void windowClosed(WindowEvent e) {}
                        @Override
                        public void windowClosing(WindowEvent e) {
                             closeIt();
                        @Override
                        public void windowDeactivated(WindowEvent e) {}
                        @Override
                        public void windowDeiconified(WindowEvent e) {}
                        @Override
                        public void windowIconified(WindowEvent e) {}
                        @Override
                        public void windowOpened(WindowEvent e) {}
              protected Vector<DBO_Referrals> buildDummyVector() {
                   Vector<DBO_Referrals> vr = new Vector<DBO_Referrals>();
                   for (int x = 0; x < 5000; x++) {
                        DBO_Referrals r = new DBO_Referrals(x+(5000*ctr));
                        vr.add(r);
                   return vr;
              protected void uninit() {
                   tblReferrals.setComponentPopupMenu(null);
                   for (Component c : popMenu.getComponents()) {
                        PropertyChangeListener[] pl = c.getPropertyChangeListeners();
                        for (PropertyChangeListener l : pl)
                             c.removePropertyChangeListener(l);
                        if (c instanceof JMenuItem) {
                             ActionListener [] al = ((JMenuItem)c).getActionListeners();
                             for (ActionListener l : al) {
                                  ((JMenuItem)c).removeActionListener(l);
                   popMenu = null;
              protected class DBO_Referrals {
                   protected long          id;
                   protected String     Employee;
                   protected String     Rep;
                   protected String     Asst;
                   protected String     Client;
                   protected String     Dates;
                   protected String     Status;
                   protected String     Home;
                   public DBO_Referrals(long id) {
                        this.id = id;
                        Employee = "Employee" + id;
                        Rep = "Rep" + id;
                        Asst = "Asst" + id;
                        Client = "Client" + id;
                        Dates = "Dates" + id;
                        Status = "Status" + id;
                        Home = "Home" + id;
                   public long getId() {
                        return id;
                   public String getEmployee() {
                        return Employee;
                   public String getRep() {
                        return Rep;
                   public String getAsst() {
                        return Asst;
                   public String getClient() {
                        return Client;
                   public String getDates() {
                        return Dates;
                   public String getStatus() {
                        return Status;
                   public String getHome() {
                        return Home;
              public class ReferralsTableModel extends AbstractTableModel {
                   protected Vector<DBO_Referrals>          data          = new Vector<DBO_Referrals>();
                   protected String[]                         sColumns     = {"id", "Employee", "Rep", "Assistant", "Client", "Date", "Status", "Home", "R"};
                   public ReferralsTableModel() {
                        super();
                   public ReferralsTableModel(Vector<DBO_Referrals> data) {
                        this();
                        this.data = data;
                   @SuppressWarnings("unchecked")
                   @Override
                   public Class getColumnClass(int col) {
                        switch (col) {
                             case 0 :
                                  return Long.class;
                             default :
                                  return String.class;
                   @Override
                   public int getColumnCount() {
                        return sColumns.length;
                   @Override
                   public int getRowCount() {
                        return data.size();
                   @Override
                   public Object getValueAt(int row, int col) {
                        if (row > data.size())
                             return null;
                        DBO_Referrals a = data.get(row);
                        switch (col) {
                             case 0 :
                                  return a.getId();
                             case 1 :
                                  return a.getEmployee();
                             case 2 :
                                  return a.getRep();
                             case 3 :
                                  return a.getAsst();
                             case 4 :
                                  return a.getClient();
                             case 5 :
                                  return a.getDates();
                             case 6 :
                                  return a.getStatus();
                             case 7 :
                                  return a.getHome();
                             case 8 :
                                  return "+";
                             default :
                                  return null;

    BTW instead of continually printing out the memory use a profiler (jvisualvm in the jdk/bin directory -> heapdump -> search on your class -> view in instances -> find nearest GC root).
    Looks like BasicPopupMenuUI doesn't remove a reference to the JRootPane immediately. As far as I can see it will be removed when another menu shows.
    As a hackish workaround you can try this in you FrmReferrals#uninit():
                for(ChangeListener listener : MenuSelectionManager.defaultManager().getChangeListeners()) {
                    if (listener.getClass().getName().contains("MenuKeyboardHelper")) {
                        try {
                            Field field = listener.getClass().getDeclaredField("menuInputMap");
                            field.setAccessible(true);
                            field.set(listener, null);
                        } catch (Exception e) {
                            // ignored
                        break;
                }Funnily enough though it isn't there when I reduce your code to a SSCCE:
    import java.awt.*;
    import javax.swing.*;
    public class TestBasicPopupMenuUILeak extends JFrame {
        public TestBasicPopupMenuUILeak() {
            super("Not collected right away");
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(
                            new JButton(new AbstractAction("Show frame") {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    EventQueue.invokeLater(new Runnable() {
                                        public void run() {
                                            JLabel label = new JLabel(
    "Right click to show popup, then close this frame."
    + "The frame with not be GCed until another (popup) menu is shown.");
                                            JPopupMenu popup = new JPopupMenu(
                                                    "Popup");
                                            popup.add("Item");
                                            label.setComponentPopupMenu(popup);
                                            // named differently so you can find it
                                            // easily in your favorite profiler
                                            JFrame frame = new TestBasicPopupMenuUILeak();
                                            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                                            frame.getContentPane().add(label);
                                            frame.pack();
                                            frame.setLocationRelativeTo(null);
                                            frame.setVisible(true);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }

  • Memory leaks with Third party classes

    Hello all,
    This is fairly known problem. But I guess, my problem gives a new dimention to the problem.
    I have an application which is developed by me. This application ideally needed to use third party classes ( obviously no source code is supplied ). These third party classes provide extra functionality required.
    The problem is, when I don't use third party classes in my application, every thing is fine. When I include third party classes, I am having memory leaks.
    Then I tried to investigate memory leaks with Optimizeit tool. It is new to me. As of now, I understood, we can identify where the memory leaks are occuring.
    finally the problem is, in order to solve this, I need some patches in the code. But I don't have source code for those classes. How to solve this problem?
    For example,
    I use a third party classes in my code like this,
    ThirdPartyMemoryLeakClass obj = new ThirdPartyMemoryLeakClass();
    This 'obj' is made static, as it takes lot of time to create this object. Obviously this object contains several references to other objects, which I can't control.
    In the process of reusing this object, I am getting memory leaks.
    Any ideas regarding, how one has to deal this type of situations? What are the issues involved with this case? Are there any similar problems, which have been solved? are most welcome.
    many thanks for your time.
    Madhav

    Decompile it using jad. Find leak.Yes, I too got the idea and tried to decompile those classes and recompile. I had some problems while recompiling. Is this is the only way to get rid of this problem?
    I was refering to powersoft.datawindow.DataStore class. Does any body here has worked on these?
    Can you suggest me how to find the memory leak causes? if you were needed to find out memory leak causes, what would be your approach?
    Madhav

  • Memory leak with 1.6.0_07 in applet using Swing

    Java Plug-in 1.6.0_07
    Using JRE version 1.6.0_07 Java HotSpot(TM) Client VM
    Windows XP - SP2
    I have a commercial application that has developed a memory leak with the introduction of the latest plugin. The applets chew up memory and eventually freeze. They did not before. Using jvisualm I see a build up of native arrays, primarily int[][] and char[]. I'm still investigating. Anyone have a similar experience?
    The Applet uses a swing interface, uses buffered images and swing timers, and regularly performs http connections to the server which result in actions via the SwingUtil.invokeLater() method.

    I am Using Internet Explorer Browser Version 6.0.Huge security hole.
    Its not throwing Error / Exception Wrap a try/catch at the highest level possible.
    Catch 'Throwable'. And log/display it somewhere.

  • Memory leak in IMAQ Write PNG File

    Hi,
    I have a labview program that I'm using to do Speckle Patter Interferometry - it takes an image, takes a second image after some time, then subtracts the original image from the first and saves the subtraction.  The process reveals fringes on an object deformed on wavelength scales.
    The problem currently is that the program seems to have a memory leak.  When I run the program, the amount of memory being used (according to Windows Task Manager) just keeps going up and up then after about 20 minutes, it crashes with the error:
    Error 1074396159
    Not enough memory for required operation
    The error is normally when the file tries to write the png file - though that is the part of the program that takes the most time so it could just be coincidence that it happens at this point in the loop.
    I've tried using the labview profiler (output attached), but can't see a particular VI that is using an abhorrent amount of memory.
    I'm fairly stuck for ideas - I've attached a library with the VI and its sub VIs - if anyone would be so kind as to give me a hand I'd be very much appreciative.  I realise that my code is quiet messy - this is my first attempt at labview (albeit quite a long way into my first attempt) so any suggestions would be much appreciated also.
    Thanks
    Sam
    Attachments:
    ESPI.llb ‏556 KB
    memory_profile.txt ‏237 KB

    Hi Sam, 
    I'm glad to hear that you managed to fix the problem in your code. I have had a look at the code you posted and I have a few suggestions on how you can improve it.
    In your code you haven't included the error clusters from the VIs. Most sub VI functions included in LabVIEW will have an Error In and Error Out port that will transfer any error information through the VI. If an error does occur in the code, the error will be passed through the rest of the VI. If a sub VI or function receives an error at its error in port the VI will not execute and the error will pass through until it reaches the end of the VI. At the end of a the VI there needs to be an Error Handler function to display the error information. As error information flows through the VI the same as the data, using error clusters is a good way to determine the flow of data through a VI. This is a good way to determine the data flow through the VI as opposed to Sequence Structures which should be used in moderation.  
    I have taken a segment of you code and made some minor modifications to demonstrate how error clusters can be used (see screenshot below).  
    Error clusters can be implemented into any logic for the stop condition of a while loop. The Unbundle by Name using the Status option can be used in conjunction with the error cluster to produce a boolean output depending on if an error has occurred. If an error does occur, the function will produce a true and if an error does not occur it will produce a false. The error cluster can also be expanded by hovering the mouse over the top or bottom of the function and dragging the grey box up or down. This is useful for when you want to produce multiple outputs from the same data, such as the histogram data in your VI.
    Another thing I noticed in you code was some redundant logic. You had set the Stop button default on your front panel to true, which meant that an inverter had to be used to stop the first while loop and the stop condition in the last while loop had been changed to Continue if True. If you had kept the stop button default to False and the stop condition of the last while loop to Stop if True, the inverter on the first while loop would not be needed. This however is only a small issue but its something you could keep in mind when writing other code.
    Hopefully these suggestions will help you to further develop you LabVIEW code. I understand that implementing these suggestions into you current code could be an issue due to the size of it, but they are good features to consider when developing any code in the future. 
    If there is anything you are unsure of please do not hesitate to post any questions. I will be more than happy to assist you.
    Kind Regards 
    Jason W.
    Applications Engineer
    National Instruments UK & Ireland

  • I am experiencing a memory leak when I write to a file in a loop.

    I am conducting a cycling test, each cycle represents about 48k of memory. I collect a selectable number of cycles into a shift register. When the chosen number of cycles is reached, I write the data to text files and then clear out the shift register. Unfortunately, I do not free up any memory space when this happens. I have been able to isolate the memory leak to the file writing function. I thought I was closing the reference when I closed the file, but apparently that is not happening. What space I free up by clearing the buffer, is cancelled by the memory required to make a reference to the file (I am guessing). This is all happening in a loop that must run as many as 500,000 times. Ideally, I
    would like to write as many as 1500 records at a time. At this point the memory leak makes this almost impossible. I have ordered some more memory, but I would rather plug the leak. I have read that LabView leaves a reference open to the file even after the file is closed. What can I do to clear the memory used up by leaving the reference open? Any insights would be very appreciated.

    The behaviour you describe is strange. Something to try: Open a refernce to the file one time before entering the loop, then inside the loop use that reference to do all the writing. Finally close the reference when the loop completes.If this doesn't work, post your code in 6.0 format and I'll be glad to look at it.Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Memory leak with large files and this code?

    Okay, so the following code will not complete. 
    Basically what I am doing is opening 5 files and generating a PDF document from the already opened Report file, which is renewed prior to the PDF export operation.  I left out the general stuff at the start.  I am also writing out the location of the PDF to a HTML file, which acts as an index of the exported PDF documents.
    I believe it is due to some sort of memory leak issue, but it could be something else or just my code.  I have not stepped through this code, but for small file sizes of say less than 40 megs per file, it works fine.  For file sizes along these lines:
    File 1 = 230 megs
    File 2,3 = 26 megs
    File 4,5 = 8 megs
    it will belch erors at the end of about the 5th iteration through the For loop.  It will complete the 5th iteration however.  Here are the errors generated:
    84   10/26/2006 9:35:15 AM Error:
    85   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p1.TDM" file is invalid.
         (Error no. 6)
    86   10/26/2006 9:40:19 AM Error:
    87   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p2.TDM" file is invalid.
         (Error no. 6)
    88   10/26/2006 9:45:17 AM Error:
    89   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p3.TDM" file is invalid.
         (Error no. 6)
    90   10/26/2006 9:53:07 AM Error:
    91   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p8.TDM" file is invalid.
         (Error no. 6)
    92   10/26/2006 10:00:39 AM Error:
    93   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p9.TDM" file is invalid.
         (Error no. 6)
    94   10/26/2006 10:01:01 AM Error:Error occured during file creation.
    95   10/26/2006 10:01:01 AM Error:
         Error in <GM315 Pa...sing.VBS> (Line: 185, Column: 5):
         File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p1.TDM" file is invalid.
         (Error no. 6)
    For files of a larger size, like:
    File 1 = 7500 megs
    File 2,3 = 80 megs
    File 4,5 = 25 megs
    This occurs after about 2-3 iterations through the loop.
    see attachment for code.
    Attachments:
    ForLoopCode.txt ‏11 KB

    i am having a similar error randomly inserted in the log 
    25   10/1/2009 1:58:36 PM Error:
    26   File handle for "C:\Program Files\Summitek\Spartan\data\tdm\S Parameter Test $SSN$ 49.TDMS" file is invalid.
         (Error no. 6)
    and
    31   10/1/2009 1:58:37 PM Error:
    32   File handle for "C:\Program Files\Summitek\Spartan\www\temp\Test_$SSN$ 49_602313172.pdf" file is invalid.
         (Error no. 6)
    it doesn't seem to be causing an immediate problem, but i have had several unexplained Diadem lockups.
    they occur in log after i use CALL DATAFILELOADSEL and CALL PICpdfexport
    help? what does this mean
    jim

  • Memory leak with CursoredStream

    I want, first, to write a large collection of data in a file, and second, remove all these data.
    I use CursoredStream to manage them.
    I first use mark() method before iterate throw values with
    while (hasMoreElements()) { nextElement(); }
    loop, and second use reset() method to move back to first row before iterate again.
    I can only use releasePrevious() method in the second iteration to avoid memory leak. But the first iteration creates objects that are not released.
    If I use this method in the first iteration, I can't iterate the second times.
    Is it a bug?
    Is there a way to destroy all the created objects?

    Once you call releasePrevious() those objects are released and can only be accessed from a new query.
    What is the IdentityMap type you have set in your project for the class you are reading and the related classes, if the class has no reference to it (from other classes) you will want to use no-identity map. If there are references then you will want to use WeakIdentityMap.
    The second time you iterate through the Cursor you will be retrieving the same instance of objects as the first time, no extra memory will be used.
    --Gordon

  • Memory leak with CGImageSourceCreateThumbnailAtIndex

    After creating a thumbnail with CGImageSourceCreateThumbnailAtIndex, CGImageRelease doesn't seem to work!? I am rendering full-size thumbnails of PDF pages, and this just leaks memory:
    void memLeakTest(CFStringRef sourcePath) {
    printf("Running memLeakTest...
    CFURLRef url = CFURLCreateWithString(NULL, sourcePath, NULL);
    CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, NULL);
    CFStringRef keys[3];
    CFTypeRef values[3];
    int n=0;
    keys[n] = kCGImageSourceCreateThumbnailFromImageAlways;
    values[n++] = kCFBooleanTrue; //If I set this to false, there is no leak, but I need the thumbnails
    keys[n] = kCGImageSourceCreateThumbnailWithTransform;
    values[n++] = kCFBooleanTrue;
    keys[n] = kCGImageSourceShouldCache;
    values[n++] = kCFBooleanFalse;
    CFDictionaryRef options;
    options = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, values, n, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CGImageRef image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);
    CFRelease( imageSource );
    CGImageRelease( image ); //Doesn't seem to have any effect. Memory continues to balloon.
    CFRelease( url );
    int main (int argc, const char * argv[]) {
    CFStringRef pathUrl = CFSTR("file:/path/to/a/big.pdf");
    while( true ) {
    memLeakTest( pathUrl );
    if( n < maxPages ) sleep(5); //Wait 5 seconds
    return 0;

    I was able to fix the memory leak using the following code:
    void memLeakTest(CFStringRef sourcePath) {
    printf("Running memLeakTest...
    CFURLRef url = CFURLCreateWithString(NULL, sourcePath, NULL);
    CFStringRef keys[10];
    CFTypeRef values[10];
    int n=0;
    //keys[n] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
    //values[n++] = kCFBooleanTrue;
    keys[n] = kCGImageSourceCreateThumbnailFromImageAlways;
    values[n++] = kCFBooleanTrue;
    keys[n] = kCGImageSourceCreateThumbnailWithTransform;
    values[n++] = kCFBooleanTrue;
    keys[n] = kCGImageSourceShouldCache;
    values[n++] = kCFBooleanFalse;
    CFDictionaryRef options;
    options = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, values, n,
    &kCFTypeDictionaryKeyCallBacks,
    &kCFTypeDictionaryValueCallBacks);
    //CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, options);
    NSImage* imageFile = [[NSImage alloc] initByReferencingURL: (NSURL *)url];
    NSData * data = [imageFile TIFFRepresentation];
    CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)data, options);
    CGImageRef image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);
    CFRelease( image );
    CFRelease( imageSource );
    [imageFile release];
    CFRelease( options );
    CFRelease( url );
    There are a number of different graphics APIs you could use. I'm no expert in any of them, so I used the simple ones. The above code requires both Objective-C and an autorelease pool, but I'm sure you could use different functions to remove those requirements.

  • Memory Leak with cloneModelFromCastMember()?

    Hello Experts!
    I have been experiencing an apparent memory leak within
    Director 11 when
    using cloneModelFromCastMember().
    I was making the assumption that calling resetWorld() on a
    w3D member
    onBeginSprite() would garbage collect any models previously
    cloned into that
    when I previously ran the movie.
    However, if I repeatedly start and stop the movie Director
    Gobbles roughly
    10Mb more memory each time. The memory usage does not reduce
    upon calling
    resetWorld()
    A good way to replicate this is to use
    cloneModelFromCastMember() on a
    largeish model in a repeat with i = 1 to 50 loop on the on
    beginSprite
    handler.
    Start and stop the movie over and over to see Director's
    memory usage hike
    up.
    Anybody have any advice why this is happening? Do I need to
    explicitly
    delete all models cloned into a member on stopMovie????
    Cheers
    Richard Smith

    Hi Zzzorro,
    Thanks for the advice!
    Why does cloning from external w3D members help? Does it
    avoid the memory
    leak? It never used to happen on Director 8.5 so it has to be
    a new Version
    10 / 11 bug right?
    I need to import several weightmapped boned characters into a
    3D member, and
    due to export issues each character has to have it's own w3D
    file.
    So I have to perform cloning at runtime to build the world. I
    also need to
    clone these characters based on the level, so I can't use
    just one single 3D
    member for both these reasons.
    Thanks for any further ideas.
    Richard Smith
    "zzzorro" <[email protected]> wrote in
    message
    news:gd4sn2$2l8$[email protected]..
    > as a rule of thumb:
    > whenever possible avoid cloneModelFromCastMember in the
    first place.
    > It is highly unrecommended and the intel engineers
    always recommended to
    > use
    > loadFile() with an external w3d file, which is much
    better than having the
    > w3d
    > file in the castlib and using cmfcm.
    > each cmfm rebuilds the whole scene and takes a lot of
    time the bigger the
    > scene is.
    > apart from glitches like leaks, which you found right
    now and other
    > things.
    >
    > I work very much with sw3d and I barely have more than
    one shockwave3d
    > member
    > in any of my movies. in very rare cases I use 2 sw3d
    members. Other than
    > that I
    > use one member where I build and load everything into
    from external w3d
    > files
    > with loadFile(), which is much more appropriate. the
    only downside is that
    > I
    > can't change the model name, but there are ways to deal
    with it.
    >

  • Memory Leak with GotoAndStop()

    I am trying to track down a solution to a memory leak within an embedded video.  If I embed a video on the timeline and then run gotoAndStop or gotoAndPlay to a specific frame every time the frame changes it takes in more memory until it crashes at about 1.7GB however if I run a straight play() on the same clip the memory usage remains constant.  I have also tried System.gc() as it is an AIR App and have tried unloadAndStop() with the embeded video being loaded into a Loader and neither can reclaim any memory.
    I am looking for a a way to resolve the memory leak or another way to be able to rapidly jump to specific frames of video as far as I know this is not possible with external flvs.
    Thanks
    Dave

    video is much like a .gif file.  if you start at frame 0 and jump to frame 30 it needs to redraw what it does nt have in frame 30  which means tellign it to start at frame 30 is the same as telling it to get all information from when it last changed which might be frame 27 to complete the frame of what should display on frame 30.
    this is why its slow to play backwards.  and best to play an flv forward.
    what i would suggest if you do not need video persay, would be to use png sequences.  but if your videos are long then i suppose it would be a greater advantage to keep it compressed.
    what is the quality as well of the video and its size and your frame rate?
    You mention that you are creating a 3d view, how is that?  do you use more than 1 swf ?
    I still think this does not sound like a play head issue, since the video is already compiled.

  • Memory leak with SystemTray

    Hello,
    I just found a memory leak in my code caused by the SystemTray, but I don't know if that is me that misused SystemTray (I add a trayIcon, then remove it, then add an another one, and so on). I know how to get around that problem, but I don't know the origin of it (my code, java bug ?). So I made the following code reproducing that leak. If someone can give me idea or advice :-)
    class MyThread extends Thread {
      ReferenceQueue<?> referenceQueue;
      public MyThread(ReferenceQueue<?> referenceQueue) {
        this.referenceQueue = referenceQueue;
      @Override
      public void run() {
        System.out.println("Starting ...");
        try {
          while (true) {
            referenceQueue.remove();
            System.out.println("We release a TrayIcon");
        } catch (InterruptedException ex) {
          Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    class MyPopup extends PopupMenu {
      static final int MAX = 1000000;
      Integer []toto = new Integer[MAX];
      public MyPopup() {
        for(int i = 0; i < MAX; i++)
          toto[i] = i;
    public class Main {
        public static void main(String[] args) {
          PopupMenu popup;
          ReferenceQueue referenceQueue = new ReferenceQueue();
          Vector<WeakReference>weakReference = new Vector<WeakReference>();
          MyThread myThread = new MyThread(referenceQueue);
          myThread.start();
          SystemTray tray = SystemTray.getSystemTray();
          TrayIcon trayIcon;
          File file = new File(<AN IMAGE HERE>);
          Image image;
          try {
            image = ImageIO.read(file);
            while(true) {
              popup = new PopupMenu();
              trayIcon = new TrayIcon(image, "Frame Title", popup);
              tray.add(trayIcon);
              tray.remove(trayIcon);
              weakReference.add(new WeakReference(trayIcon, referenceQueue));
          } catch (IOException ex) {
            Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, ex);
          } catch (AWTException e) {
              Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, e);
    }------------------------------------------- ADDED -----------------------------------
    P.S. :
    - the toto array in MyPopup is there in order to obtain quicker a OutOfMemory (OOM)
    - you may change your java parameter by fixing the allowed memory size in order to have a OOM quicker (-Xms30m -Xmx30m)
    - you must have an image in order to test this code (and set the path where <AN IMAGE HERE> is)
    - if you remove the following lines there is no OOM :
    tray.add(trayIcon);
    tray.remove(trayIcon);
    so it seems to me that TrayIcon is the origin of the OOM
    - the weak reference is there in order to see when a trayIcon can be garbage collected
    Edited by: lemmel on May 5, 2009 7:22 AM - added comments

    So I did the test and:
    - you were right about the vector, but this one was added only for debugging purpose (find the OOM cause)
    - your code sample get a OOM with my computer as well as mine (with the vector removed obviously); I made some alteration to your code see below
    could you try changing your java memory settings (see below) ?
    P.S. :
    - I first tried with your code as it was, got the OOM, then decided to give some time to the garbage collector (and later to force a call to it) by adding the lines with the tag ADDED
      import java.awt.*;
      import java.awt.image.BufferedImage;
      static class MyPopup extends PopupMenu {
      public static void main(String[] args) throws Exception{
        SystemTray tray = SystemTray.getSystemTray();
        BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
        int i = 0;                       //ADDED
        while (true) {
            PopupMenu popup = new MyPopup();
            TrayIcon newTrayIcon = new TrayIcon(image, "Frame Title", popup);
            tray.add(newTrayIcon);
            tray.remove(newTrayIcon);
            if((i%10)==0) {              //ADDED
              System.gc();               //ADDED
              System.runFinalization();  //ADDED
              Thread.sleep(100);         //ADDED
            }                            //ADDED
            i ++;                        //ADDED
        }I removed the array trick in the MyPopup class in order to be able to do at least one loop (see my settings below)
    - my environnement :
    ---- debian testing, kernel 2.6.26-1-686, libc6 2.9-4
    ---- tried with both java 6.12 and 6.13 (1.6.0_13; Java HotSpot(TM) Client VM 11.3-b02), use Netbeans NetBeans IDE 6.5 (Build 200811100001)
    ---- put those flags: -Xms5m -Xmx5m

  • Memory leak with Visa Close in loop

    I read the other posts about the memory leak problems with Visa Close, but eliminating the Visa Close from VI causes problems with read & write (it seems to go out of sync). Any suggestions? Example attached.
    Attachments:
    MKS_651C_Serial_Communication.vi ‏144 KB

    Solved the problem. I had to change the bit count and adjust sort. Removing the Visa Close did eliminate the memory leak.

  • Memory leak with jsp and beans

    The application we have created has one particular page that is designed to stay up in the browser and refresh with new information from database queries once every 60 seconds. Running with Tomcat3.2.1 and IE5.5
    The problem is that the memory usage of java.exe continues to grow until the machine crashes from out of memory. It does take more than 24 hours to crash.
    Things I have tried to do to track down the problem or eliminate the problem.
    - I have explicitly set the scope of the beans to "page"
    - I have watched the DatabaseAccess.class (the beans are all extended from this class) and put in code to watch how many instantiations of the class are made and subsequently garbage collected. This appears to be where the memory leak may reside - hundreds of instantiations from some other source than the page I am displaying.
    - the top frame makes database queries for security and display of a menu system dependant upon security clearance. It does not set any time for refresh (refresh == 0). Nor does it explicitly set a scope for the beans.
    - I have run a different jsp engine to see if this was directly related to Tomcat - same problem with resin2.0.0
    The main jsp page that is in the bottom section of the page has the following code:
    ** only the relevant lines are included here
    <%@ include file="../../common.jsp" %>
    <%
         refresh=60;
    %>
    <head>
    <%@ include file="../../meta_head.jsp" %>
    </head>
    <body bgcolor="#FFFFFF" text="#003399" link="#660099" vlink="#990099" alink="#006666" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <%@ include file="../../access.jsp" %>
    <%@ include file="../../page_title.jsp" %>
    <jsp:useBean id="Line" class="jsp.Line" scope="page" />
    <jsp:useBean id="Machine" class="jsp.Machine" scope="page"/>
    <jsp:useBean id="Alarm_log" class="jsp.Alarm_log" scope="page"/>
    contents of meta_head.jsp
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <META HTTP-EQUIV= "expires" content = "0">
    <META HTTP-EQUIV="Pragma" CONTENT="no_cache">
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache" forua="true">
    <META NAME="robots" content="NOINDEX,NOFOLLOW">
    <%
    if (refresh > 0)
    %>
    <meta http-equiv="Refresh" content="<%= refresh %>">
    <%
    If anyone has some suggestions on how to trap this memory leak, it would be terrific. Or, some other things to try to stop the instantiation of the DatabaseAccess object (perhaps setting the scope of the beans in the header to "session" or "application"?).
    Thanks in advance.
    Roberta

    jsp:useBean tags scope declaration :
    page = Create a new instance on each load.
    session = Load instance from the session, if not there, create one
    application = Load instance from the ServletContext, if not there, create one.
    Not sure how you are populating the data variables, but make sure you are closing all ResultSet, (Prepared)Statement, and Connection objects.

Maybe you are looking for