Memory Leak with new Font()

Hello all,
Not sure if this is the right place to post this but here goes. I have a program that needs to change the font of at least 250,000 letters, however after doing this the program runs slow and laggy as if changing the fonts of each letter took up memory and never released it? Here is a compilable example, Click the button at the bottom of the window and watch the letter it is currently working on. You will notice that around 200,000 it will begin to not smoothly count up anymore but count in kind of a skipping pattern. This seems to get worse the more you do it and seems to indicate to me that something is using memory and not releasing it. I'm not sure why replacing a letter's font with a new font would cause more memory to be taken up I would think if I was doing it properly it would simply replace the old font with the new one not taking anymore memory then it did before. Here is the example: This program sometimes locks up so be prepared. If someone could maybe point out what is causing this to take up more memory after changing the fonts that would be great and hopefully find a solution :) Thanks in advance.
-neptune692
* To change this template, choose Tools | Templates
* and open the template in the editor.
package paintsurface;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.List;
public class PaintSurface implements Runnable, ActionListener {
public static void main(String[] args) {
        SwingUtilities.invokeLater(new PaintSurface());
List<StringState> states = new ArrayList<StringState>();
Tableaux tableaux;
Random random = new Random();
Font font = new Font("Arial",Font.PLAIN,15);
//        Point mouselocation = new Point(0,0);
static final int WIDTH = 1000;
static final int HEIGHT = 1000;
JFrame frame = new JFrame();
JButton add;
public void run() {
        tableaux = new Tableaux();
        for (int i=250000; --i>=0;)
                addRandom();
        frame.add(tableaux, BorderLayout.CENTER);
        add = new JButton("Change Font of letters - memory leak?");
        add.addActionListener(this);
        frame.add(add, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
public void actionPerformed(ActionEvent e) {
    new Thread(new ChangeFonts()).start();
void addRandom() {
        tableaux.add(
                        Character.toString((char)('a'+random.nextInt(26))),
                        UIManager.getFont("Button.font"),
                        random.nextInt(WIDTH), random.nextInt(HEIGHT));
//THIS CLASS SEEMS TO HAVE SOME KIND OF MEMORY LEAK I'M NOT SURE?
class ChangeFonts implements Runnable {
    public void run() {
    Random rand = new Random();
        for(int i = 0; i<states.size(); i++) {
            font = new Font("Arial",Font.PLAIN,rand.nextInt(50));
            states.get(i).font = font;
            add.setText("Working on letter - "+i);
class StringState extends Rectangle {
        StringState(String str, Font font, int x, int y, int w, int h) {
                super(x, y, w, h);
                string = str;
                this.font = font;
        String string;
        Font font;
class Tableaux extends JComponent {
        Tableaux() {
                this.enableEvents(MouseEvent.MOUSE_MOTION_EVENT_MASK);
                lagState = createState("Lag", new Font("Arial",Font.BOLD,20), 0, 0);
        protected void processMouseMotionEvent(MouseEvent e) {
                repaint(lagState);
                lagState.setLocation(e.getX(), e.getY());
                repaint(lagState);
                super.processMouseMotionEvent(e);
        StringState lagState;
        StringState createState(String str, Font font, int x, int y) {
            FontMetrics metrics = getFontMetrics(font);
            int w = metrics.stringWidth(str);
            int h = metrics.getHeight();
            return new StringState(str, font, x, y-metrics.getAscent(), w, h);
        public void add(String str, Font font, int x, int y) {
                StringState state = createState(str, font, x, y);
                states.add(state);
                repaint(state);
        protected void paintComponent(Graphics g) {
                Rectangle clip = g.getClipBounds();
                FontMetrics metrics = g.getFontMetrics();
                for (StringState state : states) {
                        if (state.intersects(clip)) {
                                if (!state.font.equals(g.getFont())) {
                                        g.setFont(state.font);
                                        metrics = g.getFontMetrics();
                                g.drawString(state.string, state.x, state.y+metrics.getAscent());
                if (lagState.intersects(clip)) {
                g.setColor(Color.red);
                if (!lagState.font.equals(g.getFont())) {
                    g.setFont(lagState.font);
                    metrics = g.getFontMetrics();
                g.drawString("Lag", lagState.x, lagState.y+metrics.getAscent());
}Here is the block of code that I think is causing the problem:
//THIS CLASS SEEMS TO HAVE SOME KIND OF MEMORY LEAK I'M NOT SURE?
class ChangeFonts implements Runnable {
    public void run() {
    Random rand = new Random();
        for(int i = 0; i<states.size(); i++) {
            font = new Font("Arial",Font.PLAIN,rand.nextInt(50));
            states.get(i).font = font; // this line seems to cause the problem?
            add.setText("Working on letter - "+i);
}

neptune692 wrote:
jverd wrote:
You're creating a quarter million distinct Font objects, and obviously you must be hanging on to all of them because each character is having its font set to the newly created object. So if you have 250k chars, you're forcing it to have 250k Font objects.
Since the only difference is that rand.nextInt(50) parameter, just pre-create 50 Font objects with 0..49, stick 'em in the corresponding elements in an array, and use rand.nextInt to select the Font object to use.That does make sense but it does that when the the program is first launched and doesn't lag. But the second and third time you change the letters font it seems to lag so if it wasn't taking up more memory the second time it should perform like it did when it first launched. I don't care to investigate any further. The real problem is almost certainly the quarter million Font objects. It could be that 250k is fine, but by the time you get to 500k, it has to do a lot of GC, and that's where the slow down is coming. You might even be able to make it work better with the code you have just by tweaking the GC parameters at startup, but I wouldn't bother. Fix the code first, and then see if you have issues.
Does creating a new font for each of those letters not replace the old font object? If it didn't use more memory the second and third time I don't think you would see the skipping in the counter and the slowing down of the iterations. So it must be remembering some of the old font objects or am I wrong?Using new always creates a new object. When you do it the second time around, and call letter.setFont(newFont), the old Font object is eligible for GC. That doesn't mean it will be GCed right away though. The JVM can leave them all laying around until it runs out of memory, and then GC some or all of them.

Similar Messages

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

  • Is 16 gb  PC3-15000 (1866MHz) memory compatible with new 2.4 i7 machine??

    is 16 gb  PC3-15000 (1866MHz) memory compatible with new 2.4 i7 machine??

    No. It requires 2 - 204-pin PC-10600 (1333 MHz) DDR3 SO-DIMMs.

  • Memory Leak with the new PatchMix App Beta?

    E6300/ASUS P5B-D/2GB RAM/EMU 0404/Vista Ultimate 32bit
    The problem happens after I upgrade to the PatchMix driver set dated 9/11.
    The physical memory usage bumps from ~24M to 150M after running 24 hours, and I didnt load any FX.
    The commit size(real memory usage) is over 500M!
    This doesnt happen with the old beta driver.
    Anyone has the same problem?

    Emon wrote:
    jreid wrote:
    Dare I suggest the problem might be Vista?
    Yes? How exactly would Vista cause a memory leak within PatchMix DSP's GUI?
    Well, just a thought. The OS is ultimately responsible for all memory management, and also the low-level graphics functions that would be called by e.g. the GUI code. I just noticed that people on XP didn't seem to be having the same problems with this beta.

  • New memory leak with CS4 update?

    I just downloaded the CS4 update last night, and was doing my normal photoshop work when I had to re-start the application due to what looks like a memory leak.
    Windows XP, 3GHZ dual core ( 45 nm one ), 4 GB RAM, NVidia 9600 GT, no GPU enabled ( still comes up with that error even with newest drivers ).
    128MB TIFF file was my source.
    I had 3 layers, then copy merged all to another layer so I could liquify.
    Liquify was getting REALLY sluggish when trying to zoom, but was usable.
    After 10 minutes here, I clicked "ok" to return the results, then it said there wasn't enough memory to do it. So I had to cancel. Process was using right around 2 GB. I saved my PSD file ( around 256 MB ) and closed it. CS4 was still using around 2 GB with no documents open. So I closed CS4 and I had multiple errors pop up saying couldn't export or copy from clipboard because not enough memory.
    Brought CS4 back up and loaded in that 256MB psd file, everything was fine.

    I've been told by support that I need to un-install CS4, and re-install it and the patch in order to rectify my problem. The cause of the problem they are saying is a failed application of the patch.
    Is this a bunch of BS to keep me busy for a while? How do I know that the next time everything will install correctly?
    This will take some time to do, and I'll have to figure out how to backup all my settings/scripts.

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

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

    I suspect there is a memory leak in the function CryptGetProvParam. I made a Win32Console app in Visual Studio 2008 to recreate the problem. With the example app running it is possible to use Task Manager to see the memory usage of the .exe steadily increase
    over time.
    I called the app TestSecurityDescriptorWin32Console. Below I have pasted the contents of TestSecurityDescriptorWin32Console.cpp.
    I am looking to verify that the problem is with the CryptGetProvParam function, and if this is the case then to get the bug fixed.
    Thank you for any help
    // TestSecurityDescriptorWin32Console.cpp : Defines the entry point for the console application.
    #include "stdafx.h"
    #include <windows.h>
    HCRYPTPROV GetContext();
    void ModifyCryptProvSecurity(HCRYPTPROV hProv);
    int _tmain(int argc, _TCHAR* argv[])
    DWORD dwSDLen = 0;
    HCRYPTPROV hProv = GetContext();
    // get dwSDLen
    printf("First CryptGetProvParam: %d\n",CryptGetProvParam(hProv,PP_KEYSET_SEC_DESCR, NULL, &dwSDLen, DACL_SECURITY_INFORMATION));
    while (1) {
    BYTE* pbSD = (BYTE*)LocalAlloc(LHND,dwSDLen);
    PSECURITY_DESCRIPTOR
    pSD = (PSECURITY_DESCRIPTOR)pbSD;
    InitializeSecurityDescriptor(pSD,SECURITY_DESCRIPTOR_REVISION);
    // make pbSD size dwSDLen
    printf("Second CryptGetProvParam: %d\n",CryptGetProvParam(hProv,PP_KEYSET_SEC_DESCR, pbSD, &dwSDLen, DACL_SECURITY_INFORMATION));
    SECURITY_DESCRIPTOR*
    pSecurityDescriptor = (SECURITY_DESCRIPTOR*)pbSD;
    if (pSecurityDescriptor->Owner != NULL) FreeSid(pSecurityDescriptor->Owner);
    if (pSecurityDescriptor->Group != NULL) FreeSid(pSecurityDescriptor->Group);
    if (pSecurityDescriptor->Sacl != NULL) LocalFree(pSecurityDescriptor->Sacl);
    if (pSecurityDescriptor->Dacl != NULL) LocalFree(pSecurityDescriptor->Dacl);
    LocalFree(pbSD);
    Sleep(100);
    return 0;
    HCRYPTPROV GetContext()
    HCRYPTPROV hProv = NULL;
    HCRYPTKEY hKey = NULL;
        CHAR szPPName[100];
        DWORD dwPPNameLen = 100;
        CHAR szPPContainer[100];
        DWORD dwPPContainerLen = 100;
        // Attempt to acquire a handle to the default key container.
        if (CryptAcquireContext(
    &hProv,
    NULL,
    MS_DEF_PROV,
    PROV_RSA_FULL,
    CRYPT_MACHINE_KEYSET))
    printf("Opened default key container for crypto usage");
    else
    // Some sort of error occured...
    printf("(Allowable) Error acquiring default key container for crypto usage - ");
    // .. try to create default key container.
    if(CryptAcquireContext(
    &hProv,
    NULL,
    MS_DEF_PROV,
    PROV_RSA_FULL,
    CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET))
    printf("Created key container for crypto usage");
    else
    printf("Error Creating key container for crypto usage - ");
    return (NULL);
    // Get CSP name.
    if(CryptGetProvParam(
    hProv,
    PP_NAME,
    (BYTE *)szPPName,
    &dwPPNameLen,
    0))
    printf("Key CSP name is '%s'",szPPName);
    else
    // Error getting key container name.
    printf("Failed to retrieve CSP name - ");
    // Get name of key container.
    if(CryptGetProvParam(
    hProv,
    PP_CONTAINER,
    (BYTE *)szPPContainer,
    &dwPPContainerLen,
    0))
    printf("Key container provider name is '%s'",szPPContainer);
    else
    // Error getting key container name.
    printf("Failed to retrieve key container name - \n");
    return hProv;

    "BYTE* pbSD = (BYTE*)LocalAlloc(LHND,dwSDLen);"
    LHND? It's surprising that this doesn't crash the program. Use LPTR.
    More generally, stay away from LocalAlloc/LocalFree, use malloc/new/HeapAlloc. Use LocalAlloc only if the API you're working with specifically requires LocalAlloc, that's rare.

  • Memory leak with Power Spectrum function

    Hi
    I have a memory leak on my application. By observing with the "Desktop Execution Trace Toolkit", the Power Spectrum function (from NI_AALPro.lvlib) seems to have two "Reference leak".
    The first one refers to the function "Open VI reference"; I got around this problem by replacing the "Open VI reference" by an "Initialize" input boolean, but I don't understand the second memory leak.
    Any idea ?
    Thanks...
    (See attachments : Desktop Execution Trace + code)
    LV8.6.1 + Desktop Execution Trace Toolkit 2009
    Same problem with LV2012 + Desktop Execution Trace Toolkit 2012
    Attachments:
    DesktopExecutionTraceToolkit.png ‏82 KB
    MemoryLeakPowerSpectrum.zip ‏7 KB

    Hi Mathilde,
    Thank you for using NI Discussion Forums!
    I reproduce this problem with LV2012 + Desktop Execution Trace Toolkit 2012. I will look further into this.
    Are there many calls of this function in your code? Could it be a problem for you?
    Thank you.
    Regards,
    Audrey_P
    National Instruments France
    #adMrkt{text-align: center;font-size:11px; font-weight: bold;} #adMrkt a {text-decoration: none;} #adMrkt a:hover{font-size: 9px;} #adMrkt a span{display: none;} #adMrkt a:hover span{display: block;}
    Journées techniques : des fondamentaux aux dernières technologies pour la mesure et le contrôle/comm...

  • Memory leak with callback function

    Hi,
    I am fairly new to LabWindows and the ninetv library, i have mostly been working with LabVIEW.
    I am trying to create a basic (no GUI) c++ client that sets up subscriptions to several network variables publishing DAQ data from a PXI.
    The data for each variable is sent in a cluster and contains various datatypes along with a large int16 2D array for the data acquired(average array size is 100k in total, and the average time between data sent is 10ms). I have on average 10 of these DAQ variables.
    I am passing the same callback function as an arguement to all of these subscriptions(CNVCreateSubcription).
    It reads all the correct data, but i have one problem which is that i am experiencing a memory leak in the callback function that i pass to the CNVCreateSubscription.
    I have reduced the code one by one line and found the function that actually causes the memory leak, which is a CNVGetStructFields(). At this point in the program the data has still not been passed to the clients variables.
    This is a simplified version of the callback function, where i just unpack the cluster and get the data (only showing from one field in the cluster in the example, also not showing the decleration).
    The function is passed into to the subscribe function, like so:
    static void CNVCALLBACK SubscriberCallback(void * handle, CNVData data, void * callbackData);
    CNVCreateSubscriber (url.c_str(), SubscriberCallback, NULL, 0, CNVWaitForever, 0 , &subscriber);
    static void CNVCALLBACK SubscriberCallback(void * handle, CNVData data, void * callbackData)
    int16_t daqValue[100000];
    long unsigned int nDims;
    long unsigned int daqDims[2];
    CNVData fields[1];
    CNVDataType type;
    unsigned short int numFields;
    CNVGetDataType(data, &type, &nDims);
    CNVGetNumberOfStructFields (data, &numFields);
    CNVGetStructFields (data, fields, numFields); // <-------HERE IS THE PROBLEM, i can comment out the code after this point and it still causes a memory leak.
    CNVGetDataType(fields[0], &type, &nDims);
    CNVGetArrayDataDimensions(fields[0], nDims, acqDims);
    CNVGetArrayDataValue(fields[0], type, daqValue, daqDims[0]*daqDims[1]);
    CNVDisposeData(data);
    At the average settings i use all my systems memory (4GB) within one hour. 
    My question is, have any else experienced this and what could the problem/solution to this be?
    Thanks.
    Solved!
    Go to Solution.

    Of course.....if it is something i hate more than mistakes, it is obvious mistakes.
    Thank you for pointing it out, now everything works

Maybe you are looking for

  • Suppressing a warning message in reports 10g

    Hi All, I am getting REP-32751: Warning: Some text segments are missing warning message when ever i open a report and also while run the report in the browser. I am not able to find the missing text segments. Is there any way to suppress this warning

  • How do I merge my apple ID to my iCloud account (which was not created by the email sync offer from an OS device)

    I got an iphone. I created an iTunes account. When iCloud was release, I went to icloud.com and created myself an account. When I linked that account to my phone and wanted to sync the email, it ask me to choose an icloud ID.  Obviously, I want to us

  • Lightroom 1.4 - Note from Adobe

    I am in the process of removing Lightroom 1.4 builds from Adobe.com and recommend that those who have updated to Lightroom 1.4 revert to Lightroom 1.3.1. I will have further information shortly but I understand that there are a number of users on thi

  • Code group & selected sets

    Can anybody please tell me, Why & when it is necessary to maintain code group & selected sets. Where it is then use. What is releation between them.Will appreciate if explain with suitable example from industry. Please helpout.Newcomer in QM.

  • Adobe Servers having issues?

    Does anyone here have any idea if there's an issue with Adobe's servers today? Folio downloads from acrobat.com are far slower than usual, and downloading the updated producer tools is also very slow. Other sites aren't as slow.