Memory leak in implementing ListModel by myself

Hello,
I have created a class which implements ListModel.
In this class I overwrite "Object getElementAt(int aIndex)" function
of ListModel. What I do inside this function is I read from a
file some bytes and with that byte I create Object and return it.
I think the problem is Garbage Collector cannot remove these returned
Objects after they are shown in the JList component and when not needed
anymore.
Any help would be appriciated,
Thank you very much.
Tamer

import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
* This class is an implementation of the ListModel Interface (Model for JList),
* that operates on the binary trace file and has additional capabilities for
* handling markers.
public class TraceFileListModel implements ListModel, ActionListener
private Messageinfo mInfo;
private RuntimeInfo rtInfo;
// number of messages incl. markers
private int currentNoOfMessages;
private ListDataListener ldl;
// this timer checks for changes in the trace file size/number of messages
private javax.swing.Timer timer = new javax.swing.Timer(400, this);
// the list model to handle the markers
private DefaultListModel markerModel;
private int messageLocation = 0;
// index file
private RandomAccessFile indexFile;
// trace tool filtering index file
private RandomAccessFile indexFileTTFilterMode;
// binary trace file
private RandomAccessFile traceFile;
private String markerFilePath;
private String protocol;
private byte content[];
private Message m = new AsciiMessage();
private int messageType;
private int messageLength;
private String messageName;
// the state ID
private int processStatus;
// the state ID (redundant)
// addapted interface MS-TTMA
private int processStatusR;
// the self ID (process ID)
private int selfID;
// the process ID
private int processNumber;
// the signal/message ID
private int signalCode;
// the signal/message ID (redundant)
private int signalCodeR;
// the frame number of the signal
private int frameNumber;
// the length (in bytes) of the parameter part of the message as coded
// if the message header
private int messParaLengthCoded;
// the length (bytes) of the parameter part of the message which has
// been actually received (= the length of the message - the header )
private int messParaLengthReceived;
private int size;
private int markerCounter;
private MarkerMessage tmpMarker;
private DataInputStream das;
private Class messageClass;
private IpcMessage ipcmessage;
private byte nc[];
private StringBuffer stateName;
private AsciiMessage asciimessage;
private static final String DEFAULT_MESSAGE_REP = "not defined";
private static final String PROTOCOL_UMTS_GSM = "UMTS/GSM";
private static final String PROTOCOL_GPRS = "GPRS";
private static final String GEN_PREFIX = "Gen_";
private static final String OPEN_BRACKET = "(";
private static final String CLOSE_BRACKET = ")";
private static final String MAC_SUFFIX = "MAC FN: ";
* Creates the object.
public TraceFileListModel(String aTraceFilePath,
String aIndexFilePath,
String aMarkerFilePath,
Messageinfo aMInfo,
RuntimeInfo aRtInfo,
DefaultListModel aMarkerModel,
boolean aHasDynamicData,
String aProtocol) throws IOException
markerModel = aMarkerModel;
mInfo = aMInfo;
rtInfo = aRtInfo;
markerFilePath = aMarkerFilePath;
protocol = aProtocol;
indexFile = new RandomAccessFile(aIndexFilePath,"r");
traceFile = new RandomAccessFile(aTraceFilePath,"r");
// aHasDynamicData: tracing online that means the size of the binary trace
// file will change. Therefore the trace file size has to be taken from the
// RuntimeInfo object and is checked periodically.
if (aHasDynamicData == true) // online
if(rtInfo.getTraceToolFiltering())
indexFileTTFilterMode = new RandomAccessFile(
rtInfo.getTTFilteredModeIndexFilePath(),
"r");
rtInfo.setTopicTraceFileSize(0);
currentNoOfMessages = rtInfo.getTopicTraceFileSize();
markerModel.clear();
timer.setCoalesce(true);
timer.setRepeats(true);
timer.start();
else
if(rtInfo.getTraceToolFiltering())
indexFileTTFilterMode = new RandomAccessFile(
rtInfo.getTTFilteredModeIndexFilePath(),
"rw");
createTTFilterModeIndexFileAndLoadMarkerFile();
indexFileTTFilterMode.seek(0);
currentNoOfMessages = indexFileTTFilterMode.readInt() +
markerModel.getSize();
else
loadMarkerFile();
currentNoOfMessages = indexFile.readInt() + markerModel.getSize();
} // end of Constructor
* (Implements the ListModel.)
public int getSize()
return currentNoOfMessages;
* (Implements the ListModel.)
public Object getElementAt(int aIndex)
messageName = this.DEFAULT_MESSAGE_REP;
// the state ID
processStatus = -1;
// the state ID (redundant)
// addapted interface MS-TTMA
processStatusR = -1;
// the self ID (process ID)
selfID = -1;
// the process ID
processNumber = -1;
// the signal/message ID
signalCode = -1;
// the signal/message ID (redundant)
signalCodeR = -1;
// the frame number of the signal
frameNumber = -1;
// the length (in bytes) of the parameter part of the message as coded
// if the message header
messParaLengthCoded = -1;
// the length (bytes) of the parameter part of the message which has
// been actually received (= the length of the message - the header )
messParaLengthReceived = -1;
try
// here the number of markers before line number "aIndex" are calculated.
size = markerModel.getSize();
markerCounter = 0;
if(rtInfo.getTraceToolFiltering())
for (int i = 0; i < size; i++)
tmpMarker = (MarkerMessage) markerModel.getElementAt(i);
if (tmpMarker.lineNumberFilterMode == aIndex) return tmpMarker;
if (tmpMarker.lineNumberFilterMode > aIndex) break;
markerCounter++;
} // for loop
// the number of markers before line number "aIndex" = markerCounter
// find the read position in the binary trace file
indexFileTTFilterMode.seek((aIndex-markerCounter)*4+4);
traceFile.seek(indexFileTTFilterMode.readInt());
else
for (int i = 0; i < size; i++)
tmpMarker = (MarkerMessage) markerModel.getElementAt(i);
if (tmpMarker.lineNumber == aIndex) return tmpMarker;
if (tmpMarker.lineNumber > aIndex) break;
markerCounter++;
} // for loop
// the number of markers before line number "aIndex" = markerCounter
// find the read position in the binary trace file
indexFile.seek((aIndex-markerCounter)*12+4);
traceFile.seek(indexFile.readInt());
messageType = traceFile.readByte();
messageLength = traceFile.readShort();
if (messageLength > 0)
content = new byte[messageLength];
traceFile.read(content);
else
content = new byte[0];
if (messageType == DataStorer.IPC_ID)
das = new DataInputStream(new ByteArrayInputStream(content));
messParaLengthReceived = das.available()-
SharedConstants.IPC_MESSAGE_TRACE_HEADER_LENGTH;
if(protocol.equalsIgnoreCase(this.PROTOCOL_UMTS_GSM))
processStatus=das.readUnsignedByte();
processStatusR=das.readUnsignedByte();
else if(protocol.equalsIgnoreCase(this.PROTOCOL_GPRS))
processStatus=das.readUnsignedShort();
selfID=das.readUnsignedByte();
processNumber=das.readUnsignedByte();
signalCode=das.readUnsignedByte();
signalCodeR=das.readUnsignedByte();
frameNumber=das.readInt();
messParaLengthCoded=das.readShort();
// get the message name from the self ID/process ID
messageName=mInfo.getSignalName(processNumber,signalCode);
// Construct the Class object representing the message (by name)
messageClass=Class.forName(this.GEN_PREFIX+messageName);
// Construct the object representing the received message
ipcmessage=(IpcMessage) messageClass.newInstance();
// hand over the parameters content, frame number, state name
byte nc[] = new byte[content.length -
                             SharedConstants.IPC_MESSAGE_TRACE_HEADER_LENGTH];
System.arraycopy(content,
SharedConstants.IPC_MESSAGE_TRACE_HEADER_LENGTH,
nc,
0,
nc.length);
ipcmessage.setContent(nc);
ipcmessage.setFrameNumber(frameNumber);
// addapted interface MS-TTMA
if (processStatus < 256)
stateName =
new StringBuffer(mInfo.getStateName(selfID, processStatus));
if (selfID != processNumber)
stateName = stateName.append(this.OPEN_BRACKET);
stateName = stateName.append(mInfo.getProcessName(selfID));
stateName = stateName.append(this.CLOSE_BRACKET);
ipcmessage.setStateName(stateName.toString());
else ipcmessage.setStateName(this.MAC_SUFFIX + processStatus);
ipcmessage.setParameterLength(messParaLengthCoded);
// if the length of the parameter part coded in the trace header
// differs from the length calculated from the length of the
// received data the message is branded as defective by throwing
// an IOException
if (messParaLengthReceived != messParaLengthCoded)
throw new IOException();
// return the message object
return (Message) ipcmessage;
} // if "Ipc Message"
if (messageType == DataStorer.ASCII_ID)
// construct an Ascii Message object
asciimessage=new AsciiMessage();
// hand over the content
asciimessage.setContent(content);
// return the message object
return (Message)asciimessage;
} // if "Ascii Message"
} // try
catch(IOException ioE)
return
provideErrMsg(messageName,processStatus,selfID,processNumber,signalCode);
catch(ClassNotFoundException cnfE)
return
provideErrMsg(messageName,processStatus,selfID,processNumber,signalCode);
catch(IllegalAccessException iaE)
return
provideErrMsg(messageName,processStatus,selfID,processNumber,signalCode);
catch (InstantiationException iE)
return
provideErrMsg(messageName,processStatus,selfID,processNumber,signalCode);
return m;
} // end of method "getElementAt"
* (Implements the ListModel.)
public void addListDataListener(ListDataListener l)
ldl = l;
* (Implements the ListModel.)
public void removeListDataListener(ListDataListener l)
ldl = null;
* Provides an error message object.
public static Message provideErrMsg(String aMessageName,
int aProcessStatus,
int aSelfID,
int aProcessNumber,
int aSignalCode)
StringBuffer text = new StringBuffer("Invalid Message :");
text.append(aMessageName);
text.append(" State: ");
text.append(aProcessStatus);
text.append(" SelfID/ProcessID: ");
text.append(aSelfID);
text.append("/");
text.append(aProcessNumber);
text.append(" SignalID: ");
text.append(aSignalCode);
AsciiMessage message = new AsciiMessage();
message.setContent(text.toString().getBytes());
return message;
} // end of method "provideErrorMessage"
* Stop the timer that supervises the (dynamic) trace file size/number of
* messages. From now on the number of trace messages is fixed.
public void setNoDynamic()
if (timer.isRunning() == true) timer.stop();
int tmpSize = rtInfo.getTopicTraceFileSize();
if (tmpSize > currentNoOfMessages)
ListDataEvent event = new ListDataEvent(this,
ListDataEvent.INTERVAL_ADDED,
currentNoOfMessages, tmpSize-1);
ldl.intervalAdded(event);
currentNoOfMessages = tmpSize;
} // end of method "setDynamicData"
* This method supervises the size of the binary trace file.
public void actionPerformed(ActionEvent e)
size = rtInfo.getTopicTraceFileSize();
if (size > currentNoOfMessages)
ListDataEvent event = new ListDataEvent(this,
ListDataEvent.INTERVAL_ADDED,
currentNoOfMessages, size-1);
ldl.intervalAdded(event);
currentNoOfMessages = size;
} // end of method "actionPerformed"
* Close the used index file and binary trace file explicitly.
private void close() throws IOException
indexFile.close();
traceFile.close();
} // end of method "close"
} // end of TraceFileListModel
Most important part is:
messageClass=Class.forName(this.GEN_PREFIX+messageName);
// Construct the object representing the received message
ipcmessage=(IpcMessage) messageClass.newInstance();
// hand over the parameters content, frame number, state name
byte nc[] = new byte[content.length -SharedConstants.IPC_MESSAGE_TRACE_HEADER_LENGTH];
System.arraycopy(content,
SharedConstants.IPC_MESSAGE_TRACE_HEADER_LENGTH,
nc,
0,
nc.length);
ipcmessage.setContent(nc);
then I return ipcmessage. And I think when I scroll down/up
and when this message is not visiable it should be deleted by Garbage
Collector. Which I think doesnot happen.

Similar Messages

  • Memory leak in JSpinner implementation (maybe others?)

    Hi,
    I am developing an application using Java and Swing, and have run into some problems with memory leaks. After examining the source code and making an example program (provided below), I can only come to the conclusion that there is a bug in the implementation of JSpinner in Sun Java 1.6.0_03.
    If one uses a custom model with the JSpinner, it attaches itself as a listener to the model. However, it never removes the listening connection, even if the model is changed. This causes the JSpinner to be kept in memory as long as the model exists, even if all other references to the component have been removed.
    An example program is available at http://eddie.dy.fi/~sampo/ModelTest.java . It is a simple swing program that has the JSpinner and two buttons, the first of which writes to stdout the listeners of the original model and the second changes the spinner model to a newly-created model. A sample output is below:
    Running on 1.6.0_03 from Sun Microsystems Inc.
    Listeners before connecting to JSpinner:
      Model value is 0, 0 listeners connected:
    Listeners after connecting to JSpinner:
      Model value is 0, 2 listeners connected:
      1: interface javax.swing.event.ChangeListener
      2: javax.swing.JSpinner$ModelListener@9971ad
    Listeners now:
      Model value is 8, 2 listeners connected:
      1: interface javax.swing.event.ChangeListener
      2: javax.swing.JSpinner$ModelListener@9971ad
    Changing spinner model.
    Listeners now:
      Model value is 8, 2 listeners connected:
      1: interface javax.swing.event.ChangeListener
      2: javax.swing.JSpinner$ModelListener@9971adThis shows that even though the model of the JSpinner has been changed, it still listens to the original model. I haven't looked at other components whether they retain connections to the old models as well.
    In my case, I have an adaptor-model which provides a SpinnerModel interface to the actual data. The adaptor is implemented so that it listens to the underlying model only when it itself is being listened to. If the JComponents using the model were to remove the listening connections, it, too, would be automatically garbage-collected. However, since JSpinner does not remove the connections, the adaptor also continues to listen to the underlying model, and neither can be garbage-collected.
    All in all, the listener-connections seem to be a very easy place to make memory leaks in Java and especially in Swing. However, as I see it, it would be a simple matter to make everything work automatically with one simple rule: Listen to the models only when necessary.
    If a component is hidden (or alternatively has no contact to a parent JFrame or equivalent), it does not need to listen to the model and should remove the connections. When the component is again set visible (or connected to a frame) it can re-add the connections and re-read the current model values just as it does when initializing the component. Similarly, any adaptor-models should listen to the underlying model only when it itself is being listened to.
    If the components were implemented in this way, one could simply remove a component from the frame and throw it away, and automatically any listener-connections will be removed and it can be garbage-collected. Similarly any adaptor-models are collected when they are no longer in use.
    Changing the API implementation in this way would not require any changes to applications, as the only thing that changes are the listener-connections. Currently used separate connection-removing methods should still work, though they would be unnecessary any more. The API would look exactly the same from the view of an application programmer, only that she would not need to care about remnant listening connections. (As far as I can tell, the current API specification would allow the API to be implemented as described above, but it should of course require it to be implemented in such a way.)
    Am I missing something, or is there some valid reason why the API is not implemented like this?
    PS. I'm new to these forums, so if there is a better place to post these reports, please tell me. Thanks.

    Another cognition: It's the following code, that causes the memory to be accumulated:
    obj = m_orb.resolve_initial_references("NameService");
    ctx = NamingContextExtHelper.narrow(obj);For the first 4 calls to this code the memory usage of the nameservice is unchanged. From the 5th to the 8th call, it's increased by approx. 10KB per call. And thenceforward (beginning with the 9th call) it's increasing by approx. 10MB.
    What's going wrong here?

  • Memory leak using xslprocessor.valueof in 11.1.0.6.0 - 64bit ??

    My company has made the decision to do all of our internal inter-system communication using XML. Often we may need to transfer thousands of records from one system to another and due to this (and the 32K limit in prior versions) we're implementing it in 11g. Currently we have Oracle 11g Enterprise Edition Release 11.1.0.6.0 on 64 bit Linux.
    This is a completely network/memory setup - the XML data comes in using UTL_HTTP and is stored in a CLOB in memory and then converted to a DOMDocument variable and finally the relevant data is extracted using xslprocessor.valueof calls.
    While this is working fine for smaller datasets, I've discovered that repeated calls with very large documents cause the xslprocessor to run out of memory with the following message:
    ERROR at line 1:
    ORA-04030: out of process memory when trying to allocate 21256 bytes
    (qmxdContextEnc,)
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1010
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1036
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1044
    ORA-06512: at "SCOTT.UTL_INTERFACE_PKG", line 206
    ORA-06512: at line 28
    Elapsed: 00:03:32.45
    SQL>
    From further testing, it appears that the failure occurs after approximately 161,500 calls to xslprocessor.valueof however I'm sure this is dependent on the amount of server memory available (6 GB in my case).
    I expect that we will try and log a TAR on this, but my DBA is on vacation right now. Has anyone else tried calling the xslprocessor 200,000 times in a single session?
    I've tried to make my test code as simple as possible in order to track down the problem. This first block simply iterates through all of our offices asking for all of the employees at that office (there are 140 offices in the table).
    DECLARE
    CURSOR c_offices IS
    SELECT office_id
    FROM offices
    ORDER BY office_id;
    r_offices C_OFFICES%ROWTYPE;
    BEGIN
    OPEN c_offices;
    LOOP
    FETCH c_offices INTO r_offices;
    EXIT WHEN c_offices%NOTFOUND;
    utl_interface_pkg.get_employees(r_offices.office_id);
    END LOOP;
    CLOSE c_offices;
    END;
    Normally I'd be returning a collection of result data from this procedure, however I'm trying to make things as simple as possible and make sure I'm not causing the memory leak myself.
    Below is what makes the SOAP calls (using the widely circulated UTL_SOAP_API) to get our data and then extracts the relevant parts. Each office (call) should return between 200 and 1200 employee records.
    PROCEDURE get_employees (p_office_id IN VARCHAR2)
    l_request utl_soap_api.t_request;
    l_response utl_soap_api.t_response;
    l_data_clob CLOB;
    l_xml_namespace VARCHAR2(100) := 'xmlns="' || G_XMLNS_PREFIX || 'EMP.wsGetEmployees"';
    l_xml_doc xmldom.DOMDocument;
    l_node_list xmldom.DOMNodeList;
    l_node xmldom.DOMNode;
    parser xmlparser.Parser;
    l_emp_id NUMBER;
    l_emp_first_name VARCHAR2(100);
    l_emp_last_name VARCHAR2(100);
    BEGIN
    --Set our authentication information.
    utl_soap_api.set_proxy_authentication(p_username => G_AUTH_USER, p_password => G_AUTH_PASS);
    l_request := utl_soap_api.new_request(p_method => 'wsGetEmployees',
    p_namespace => l_xml_namespace);
    utl_soap_api.add_parameter(p_request => l_request,
    p_name => 'officeId',
    p_type => 'xsd:string',
    p_value => p_office_id);
    l_response := utl_soap_api.invoke(p_request => l_request,
    p_url => G_SOAP_URL,
    p_action => 'wsGetEmployees');
    dbms_lob.createtemporary(l_data_clob, cache=>FALSE);
    l_data_clob := utl_soap_api.get_return_clob_value(p_response => l_response,
    p_name => '*',
    p_namespace => l_xml_namespace);
    l_data_clob := DBMS_XMLGEN.CONVERT(l_data_clob, 1); --Storing in CLOB converted symbols (<">) into escaped values (&lt;, &qt;, &gt;).  We need to CONVERT them back.
    parser := xmlparser.newParser;
    xmlparser.parseClob(parser, l_data_clob);
    dbms_lob.freetemporary(l_data_clob);
    l_xml_doc := xmlparser.getDocument(parser);
    xmlparser.freeparser(parser);
    l_node_list := xslprocessor.selectNodes(xmldom.makeNode(l_xml_doc),'/employees/employee');
    FOR i_emp IN 0 .. (xmldom.getLength(l_node_list) - 1)
    LOOP
    l_node := xmldom.item(l_node_list, i_emp);
    l_emp_id := dbms_xslprocessor.valueOf(l_node, 'EMPLOYEEID');
    l_emp_first_name := dbms_xslprocessor.valueOf(l_node, 'FIRSTNAME');
    l_emp_last_name := dbms_xslprocessor.valueOf(l_node, 'LASTNAME');
    END LOOP;
    xmldom.freeDocument(l_xml_doc);
    END get_employees;
    All of this works just fine for smaller result sets, or fewer iterations (only the first two or three offices). Even up to the point of failure the data is being extracted correctly - it just eventually runs out of memory. Is there any way to free up the xslprocessor? I've even tried issuing DBMS_SESSION.FREE_UNUSED_USER_MEMORY but it makes no difference.

    Replying to both of you -
    Line 206 is the first call to xslprocessor.valueof:
    LINE TEXT
    206 l_emp_id := dbms_xslprocessor.valueOf(l_node, 'EMPLOYEEID');
    This is one function inside of a larger package (the UTL_INTERFACE_PKG). The package is just a grouping of these functions - one for each type of SOAP interface we're using. None of the others exhibited this problem, but then none of them return anywhere near this much data either.
    Here is the contents of V$TEMPORARY_LOBS immediately after the crash:
    SID CACHE_LOBS NOCACHE_LOBS ABSTRACT_LOBS
    132 0 0 0
    148 19 1 0
    SID 132 is a SYS session and SID 148 is mine.
    I've discovered with further testing that if I comment out all of the xslprocessor.valueof calls except for the first one the code will complete successfully. It executes the valueof call 99,463 times. If I then uncomment one of those additional calls, we double the number of executions to a theoretical 198,926 (which is greater than the 161,500 point where it usually crashes) and it runs out of memory again.

  • Help needed: Memory leak causing system crashing...

    Hello guys,
    As helped and suggested by Ben and Guenter, I am opening a new post in order to get help from more people here. A little background first...  
    We are doing LabView DAQ using a cDAQ9714 module (with AI card 9203 and AO card 9265) at a customer site. We run the excutable on a NI PC (PPC-2115) and had a couples of times (3 so far) that the PC just gone freeze (which is back to normal after a rebooting). After monitor the code running on my own PC for 2 days, I noticed there is a memory leak (memory usage increased 6% after one day run). Now the question is, where the leak is??? 
    As a newbee in LabView, I tried to figure it out by myself, but not very sucessful so far. So I think it's probably better to post my code here so you experts can help me with some suggestions. (Ben, I also attached the block diagram in PDF for you) Please forgive me that my code is not written in good manner - I'm not really a trained programmer but more like a self-educated user. I put all the sequence structures in flat as I think this might be easier to read, which makes it quite wide, really wide.
    This is the only VI for my program. Basically what I am doing is the following:
    1. Initialization of all parameters
    2. Read seven 4-20mA current inputs from the 9203 card
    3. Process the raw data and calculate the "corrected" values (I used a few formula nodes)
    4. Output 7 4-20mA current via 9265 card (then to customer's DCS)
    5. Data collection/calculation/outputing are done in a big while loop. I set wait time as 5 secs to save cpu some jucie
    6. There is a configuration file I read/save every cycle in case system reboot. Also I do data logging to a file (every 10min by default).
    7. Some other small things like local display and stuff.
    Again I know my code probably in a mess and hard to read to you guys, but I truely appreciate any comments you provide! Thanks in advance!
    Rgds,
    Harry
    Attachments:
    Debug-Harry_0921.vi ‏379 KB
    Debug-Harry_0921 BD.pdf ‏842 KB

    Well, I'll at least give you points for neatness. However, that is about it.
    I didn't really look through all of your logic but I would highly recommend that you check out the examples for implementing state machines. Your application suffers greatly in that once you start you basically jumped off the cliff. There is no way to alter your flow. Once in the sequence structure you MUST execute every frame. If you use a state machine architecture you can take advantage of shift registers and eliminate most of your local variables. You will also be able to stop execution if necessary such as a user abort or an error. Definitely look at using subVIs. Try to avoid implementing most of your program in formula nodes. You have basically written most of your processing there. While formula nodes are easier for very complex equations most of what you have can easily be done in native LabVIEW code. Also if you create subVIs you can iterate over the data sets. You don't need to duplicate the code for every data set.
    I tell this to new folks all the time. Take some time to get comfortable with data flow programming. It is a different paradigm than sequential text based languages but once you learn it it is extremely powerful. All your data flow to control execution rather than relying on the sequence frame structure. A state machine will also help quite a bit.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Allocated memory pool was not deleted! 1 GB memory leak is too much for me!

    Dear Sirs. I found that DB environment, that was configured to use 1 GB cache size, won't free it when closed! Why? First I tried to open and close environment and got the following:
    Detected memory leaks!
    Dumping objects ->
    {596} normal block at 0x01970040, 1048596 bytes long.
    Data: < > 14 00 10 00 DB DB DB DB 0B 00 10 00 01 00 00 00
    {578} normal block at 0x00397978, 464 bytes long.
    Data: < > D0 01 00 00 DB DB DB DB C7 01 00 00 01 00 00 00
    Object dump complete.
    I have and idea that BDB will reuse the memory, rite? OK, let's try to create the same environment and open it. After environment was opened, closed, opened again and again closed, I got the following:
    Detected memory leaks!
    Dumping objects ->
    {3663} normal block at 0x01B80040, 1048596 bytes long.
    Data: < > 14 00 10 00 DB DB DB DB 0B 00 10 00 01 00 00 00
    {3645} normal block at 0x00396E60, 464 bytes long.
    Data: < > D0 01 00 00 DB DB DB DB C7 01 00 00 01 00 00 00
    {596} normal block at 0x01970040, 1048596 bytes long.
    Data: < > 14 00 10 00 DB DB DB DB 0B 00 10 00 01 00 00 00
    {578} normal block at 0x00397978, 464 bytes long.
    Data: < > D0 01 00 00 DB DB DB DB C7 01 00 00 01 00 00 00
    Object dump complete.
    So memory was not reused, nor deallocated.
    By the way, you may be interested in other leak I found, but fixed, see
    Replication manager memory leak when setting local site information.
    This leak is more serious, I am not sure I will fix it quickly. Maybe I'm doing something wrong? Could you please suggest something?
    Thanks in advance!
    With regards,
    Vladislav.

    OK, the problem solved by fixing code in file 'log.c', method '__log_dbenv_refresh'.
    Just added the code that deallocates memory of bulk buffer.
    if (IS_ENV_REPLICATED(dbenv))
    if (lp->bulk_buf != INVALID_ROFF)
    __db_shalloc_free(&dblp->reginfo, lp->bulk_buf);
    lp->bulk_buf = INVALID_ROFF;
    lp->bulk_len = 0;
    lp->bulk_off = 0;
    It was allocated in the '__log_open' function, by the following code:
              lp->ready_lsn = lp->lsn;
              if (IS_ENV_REPLICATED(dbenv)) {
                   if ((ret = __db_shalloc(&dblp->reginfo, MEGABYTE, 0,
                   &bulk)) != 0)
                        goto err;
                   lp->bulk_buf = R_OFFSET(&dblp->reginfo, bulk);
                   lp->bulk_len = MEGABYTE;
                   lp->bulk_off = 0;
              } else {
                   lp->bulk_buf = INVALID_ROFF;
                   lp->bulk_len = 0;
                   lp->bulk_off = 0;
    Sorry for time taken to read my posts, I was really needy in quick help, but solved problems myself.

  • DataSocket memory leak problem (2VO0SF00) -- more info?

    When upgrading to LabVIEW 8.5 recently, I noticed the following known issue in the readme file:
    "ID: 2VO0SF00
    DataSocket/OPC Leaks Memory using ActiveX VIs to perform open-write-close repeatedly
    If you call the DataSocket Open, DataSocket Write, and DataSocket Close functions in succession repeatedly, LabVIEW leaks memory. Workaround — To correct this problem, call the DataSocket Open function once, use the DataSocket Write function to write multiple times, and then use the DataSocket Close function."
    Looking back, I think this problem may have been present in previous LabVIEW releases as well, and might be giving rise to a problem that's been dogging me for quite some time (see my thread, "Error 66 with DataSockets", http://forums.ni.com/ni/board/message?board.id=170&thread.id=187206), in addition to general slow/glitchy behaviour when my VI's have been running continuously for a long time. But in order to determine whether or not this issue affects me, and how I should go about fixing it in the context of my own programs, I need a bit more information about the nature of the issue itself and the inner workings of the DataSocket VI's. Any help or insight the community can provide into this would be greatly appreciated!
    Here are my questions:
    It is my understanding from the "known issue" description above that the memory leak happens when you have a DS Open wired to a DS Write wired to a DS Close, all inside a loop (example 1), and that the suggested workaround would be to move the DS Open and DS Close functions out of the loop on opposite sides, wired to the DS Write which remains inside the loop (example 2). Is this correct?
    Does this leak also happen when performing DS open-read-close's repeatedly (example 3)?
    What happens when a DS Write (or DS Read) is called without a corresponding DS Open and DS Close (examples 4a and 4b)? Does it implicitly do a DS open before doing the write operation and a DS close afterwards? What I'm getting at is this: would having an isolated DS Write (or DS Read) inside a loop, not connected to any DS Open or DS Close functions at all, cause this same memory leak?
    If one computer is running the DS server and a second computer is running the VI with the repeated open-write-close's, on which computer does the memory leak occur?
    In my question #1 workaround (example 2), the DS Open and DS Close outside the loop are routed through a shift register and in to and out of the DS Write inside the loop. If the DS connection id goes into the DS Write "connection in" and then splits and goes around the DS Write and out to the DS Close, without coming out of the DS Write "connection out" (example 5), will the memory leak still be avoided? I.e. if the DS Write function doesn't have anything connected to its "connection out", will it try to do an implicit DS Close?
    If the VI causing the memory leak is stopped, but LabVIEW stays running, will the leaked memory be reclaimed? What if the VI is closed? What if all of LabVIEW is closed?
    FYI, in the examples above "x1a" is a statically-defined DataSocket on the DS server running on the computer Max, to which the computer running the example VI's has read/write access. My actual application has numerous VI's and hundreds of DataSocket items, many of which are written to / read from every 50-100 ms in the style of examples 4a and 4b.
    Does anyone have any idea about this stuff?
    Thanks in advance,
    Patrick
    Attachments:
    examples_jpg1.zip ‏63 KB
    examples_vi1.zip ‏40 KB

    Hi Meghan,
    Yes, some of the larger VIs in my application do write to / read from several hundred DataSockets, so it's not feasible to use shift registers for each one individually, and hence why I'm passing the references into an array, etc.
    Your Alternate Solution 2 is more along the lines of something that would work for me. However, my actual code has a lot of nested loops, sequences and DataSocket items which are not all written to in the same frame, so this solution would still be difficult to implement: it would be cumbersome to unpack the entire 500-element reference id array and build a new one (maintaining the positions and values of the unaffected elements) every time I write to some small subset of the DataSockets.
    I think I have a solution which solves the problem and is also scalable to the size of my application -- I've attached it as Example 7. Do you think this will avoid the memory leak? It's the same as your Alternate Solution 2, except that instead of building a new array out of the DS Write reference outs, each reference out replaces the appropriate element of the original array.
    If I understand you correctly, in order to avoid implicit reference opens and closes, a DS Write needs to have both it's reference in and reference out wired to something. Thus, even though my Example 7 replaces an element of the array with an identical value, and therefore doesn't actually change the array (which would be a silly thing to do normally), the DS Writes have their reference outs wired to something, and eventually in a convoluted way to a DS Close, so it should avoid the memory leak.
    Just out of curiosity (I don't think anything like this would apply to my application or any fixes I implement), when would the implicit reference close happen in the attached Example 8? The DS Write has its reference in and reference out both connected to temporally "adjacent" DS Writes via the shift register, so perhaps it wouldn't try to close the reference on each loop iteration? Or would it look into the future and see that there is no DS Close and decide to implicitly do that itself? Or maybe only the DS Write on the last loop iteration does this?
    Thanks for bearing with me through this,
    Patrick
    Attachments:
    example73.JPG ‏40 KB
    example83.JPG ‏14 KB

  • Memory Leak Issue in OBIEE 11g

    Hi,
    We have OBIEE 11.1.1.5 installed on a 32-bit Windows Server. We had almost 10GB of free space yesterday, but after a few users logged in, the free space started coming down until we were left with no space at all.
    Since then we have removed all the files that we could and created more and more space, but OBIEE seems to be eating it all up. I have seen a few posts for such issues with the Linux Systems. Has anyone faced this with windows? Also, is there any solution for this.
    Thanks,
    Naman

    Hi Naman,
    Oracle has provided set of patches to avoid memory leaks.
    1) For memory leak with OPMN, apply the following patches:
    Patch:12920592: OPMN HAS MEMORY LEAK
    Patch:12989751: OPMN MEMORY STILL GAINS AFTER APPLYING PATCH#12920592
    2) For the Presentation Server (sawserver) issue, apply the patch:
    Patch:13102881: DATALAYOUT METADATA IMPLEMENTATION HEAP INTENSIVE
    Rgds,
    Dpka

  • HTTPService + XML Load + Memory Leak

    Hi all....
    I have noticed a memory leak in my application. This leak was
    not apparent when the application was completed some months back
    which is what left me a little confused as all I have done since
    was upgrade to Flex 3 and possibly updated / changed my Flash
    player.
    I think I have found the cause to this problem (below) but am
    not 100% sure that it is the "actual" problem or any reasons to
    back my thoughts up, so have listed what I have checked / tried
    along the way (maybe I have missed something)....
    My Discovery Process:
    I started profiling my application but did not find anything
    out of the ordinary. I did a code walk-through double checking I
    had cleaned up after myself, removing and even nulling all items
    etc but still to now success - the leak is still there.
    I have profiled the app in the profiler for reasonably long
    periods of time.
    All the classes etc being used within the app are consistent
    in size and instance amount and there is no sign of any apparent
    leak.
    I am using a HTTPService that is loading XML data which I am
    refreshing every 5 seconds. On this 5 second data refresh some
    class instances are incremented but are restored to the expected
    amount after a GC has occurred. The GC seems to take longer, the
    longer the app is running, therefore more and more instances are
    being added to the app, but when the GC eventually runs it "seems"
    to clear these instances to the expected amount.
    After scratching my head for a while I decided to make a copy
    of my application, rip everything out, and focus in my data load,
    where I found a problem!
    I have now just a HTTPService that loads an XML file every 5
    seconds, and this is all I currently have in the app (as I ripped
    the rest of the code out), e.g:
    Code:
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    ....... creationComplete="initApp()" >
    <mx:HTTPService
    id="httpServiceResults"
    url="
    http://myIP:myPort/myRoot/myXML.cfm"
    resultFormat="e4x"
    result="httpResultHandler(event)" />
    <script....... >
    private var timerPulse:Timer;
    private function initApp():void
    httpServiceResults.send();
    timerPulse = new Timer(5000, 0);
    private function httpResultHandler(event:ResultEvent):void
    timerPulse.start();
    timerPulse.addEventListener(TimerEvent.TIMER, timerRefresh);
    public function timerRefresh(eventObj:TimerEvent):void
    timerPulse.stop();
    timerPulse.removeEventListener(TimerEvent.TIMER,
    timerRefresh);
    timerPulse.reset();
    httpServiceResults.send();
    </script>
    </mx:Application>
    This is pretty much the code I am currently using and it
    leaks.
    I ran and monitored this in both the profiler and the
    activity / task manager, and after running the app for 1800 seconds
    (30 min) in the profiler, the memory size grew from 50mg to 165mg
    just sending the HTTPService.
    I tried loading the service in multiple ways including in AS
    rather than MXML creating new instances of it each time, resetting
    it, nulling it etc... but nothing prevented this memory increase.
    I then tried to load the XML using different methods such as
    using the URLRequest and URLLoader which again caused a memory
    leak.
    What still confuses me is that this leak did not exist in the
    previous version and not a great deal has changed since then apart
    from upgrading to Flex 3 and possibly upgrading my Flash payer
    (which I believe is a possible cause)
    After looking into this issue a bit more deeply, I read a few
    blogs / forums and other people are experiencing the same problems
    - even with a lot bigger leaks in some cases all when reloading
    large sets of XML data into Flex - however, I as of yet found no
    solution to this leak - people with a similar problem believe it is
    not due to a memory leak more a GC error, and others pointing
    towards the Flash Player itself that is leaking - I don't really
    know.
    Findings so far during investigation of this issue:
    * App leaks for both HTTPService and ULRRequest / URLLoader
    methods
    * App only leaks when calling a data loader
    * The size of the leak seems to depend on the size of the
    XML being loaded
    * The size of the leak also seems to be affected by the
    applications heaviness - the greater seems to enhance the leak
    An interesting factor I have noticed is that if I copy the
    XML from my "myXML.cfm" that I link to in my HTTPService and copy
    the contents of the file into my own XML file stored within the
    Flex project root itself: ""myXML.xml"" the leak disappears... like
    it seems to link when loading the XML over a network, however as my
    network knowledge is not great I am not sure what to make of this -
    any ideas???
    Could the connection to the XML document cause leaks??? is
    there anything else that could cause this leak??? have I something
    in my code sample that could cause this leak??? or could any of the
    other things I have mentioed cause this leak???
    Any help / ideas would be greatly appreciated.
    Thanks,
    Jon.

    I also observed heavy memory leak from using httpservice with
    XML data. I am using Flex3 builder under Linux. My Flex application
    polls httpservice every 10 seconds. The reply is a short XML
    message less than 100 bytes. This simple polling will consume 30+
    MB of memory every hour. I leave it idling for several hours and it
    took 200 MB of memory. No sign of garbage collection at all.

  • Memory leak in Application

    Hi,
    we're load testing an application using Coherence. It uses a distributed cache, with an web application as the client, and separate cache servers implementing a Cache Store.
    We're getting several memory leaks and one area that was reported was a great number of instances for the com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$GetRequest class.
    Does anybody know what could cause these instances to be left hanging around? I think the Coherence classes ar a symptom of another problem rather than an issue with Coherence itself but it would be useful to know what could cause these objects to be left in the heap.
    Thanks
    Mike

    After further load testing, our application definitely seems to be leaking Coherence objects.
    The classes seem to be com.tangosol.util.Binary &
    com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$GetRequest.
    During testing, the number of Binary objects rose 0 to about 9000 and the number of GetRequest objects rose from 0 to about 3600 in two hours.
    The application stores objects in the cache and updates them, the main operation being to add to a very long log string required by the client to these objects, which represent sessions.
    Our test keeps a constant number of these objects in the cache during the run, removing the same number it creates after it has ramped up to full load testing.
    The application is stateless, it recieves frequent requests to get an object from the cache, work on it and put it back in the cache. The cache also has a cache store to persist the data to a database.
    Are there any references to the cache objects that would stop them being garbage collected?
    Our whole application is based in a simple stateless reqest/response operation and I cannot see where the huge number of objects is coming from.
    Mike

  • Memory leak in Jain-SIP ?

    Hi there.
    We implemented a SIP gateway to MS OCS 2007 using
    Jain-SIP version 1.2.1906.
    One problem we have is memory consumption.
    Using jconsole we found out that memory is not
    completely released when SIP clients log out.
    E.g. the following classes keep on accumulating:
    53134 instances of class gov.nist.core.NameValueList
    41730 instances of class gov.nist.core.NameValue
    20330 instances of class gov.nist.core.Host
    20330 instances of class gov.nist.core.HostPort
    19767 instances of class gov.nist.core.DuplicateNameValueList
    19767 instances of class gov.nist.core.MultiValueMapImpl
    16162 instances of class gov.nist.javax.sip.address.Authority
    16162 instances of class gov.nist.javax.sip.address.SipUri
    13570 instances of class gov.nist.javax.sip.address.UserInfo
    12261 instances of class gov.nist.javax.sip.address.AddressImpl
    5210 instances of class gov.nist.javax.sip.header.Protocol
    5210 instances of class gov.nist.javax.sip.header.Via
    4168 instances of class gov.nist.javax.sip.header.CallID
    4168 instances of class gov.nist.javax.sip.header.CallIdentifier
    3901 instances of class gov.nist.javax.sip.header.CSeq
    3901 instances of class gov.nist.javax.sip.header.ContentLength
    3901 instances of class gov.nist.javax.sip.header.From
    3901 instances of class gov.nist.javax.sip.header.MaxForwards
    3901 instances of class gov.nist.javax.sip.header.RequestLine
    3901 instances of class gov.nist.javax.sip.header.To
    3901 instances of class gov.nist.javax.sip.header.ViaList
    3901 instances of class gov.nist.javax.sip.message.SIPRequest
    3901 instances of class gov.nist.javax.sip.stack.SIPTransaction$TransactionSemaphore
    2858 instances of class gov.nist.javax.sip.DialogFilter
    2618 instances of class gov.nist.javax.sip.header.Route
    2618 instances of class gov.nist.javax.sip.header.RouteList
    2592 instances of class gov.nist.javax.sip.stack.SIPServerTransaction
    2590 instances of class gov.nist.javax.sip.header.ContentDisposition
    2590 instances of class gov.nist.javax.sip.header.ContentType
    2590 instances of class gov.nist.javax.sip.header.MediaRange
    1579 instances of class org.apache.xmlbeans.SchemaType$Ref
    1309 instances of class gov.nist.javax.sip.header.UserAgent
    1309 instances of class gov.nist.javax.sip.parser.Pipeline
    1309 instances of class gov.nist.javax.sip.parser.PipelinedMsgParser
    1309 instances of class gov.nist.javax.sip.parser.StringMsgParser
    1309 instances of class gov.nist.javax.sip.stack.HopImpl
    1309 instances of class gov.nist.javax.sip.stack.SIPClientTransaction
    1309 instances of class gov.nist.javax.sip.stack.SIPClientTransaction$TransactionTimer
    1309 instances of class gov.nist.javax.sip.stack.SIPDialog
    These all are classes from the SIP stack aren't they ?
    Are there any known issues with memory leaks
    in Jain-SIP ?
    Is it probably a configuration issue with
    the properties/parameters for the SIP stack ?
    (There is a property gov.nist.javax.sip.AGGRESSIVE_CLEANUP which we set
    to TRUE but it didn't help)
    Do we miss to release/initialize anything in the SIP stack manually ?
    Thanks a lot in advance,
    Fred

    Nobody else seems ton have this problem. I haven't run my SIP code for as long as a week at a time but i didn't notice any undue memory usage, and I also trawled inside the source a lot without seeing anything odd. So is it your code leaking? Are you sure you're releasing everything to do with a conversation when it ends? Rather than say accumulating things in some static data structure?

  • Memory Leak in TCL UDP socket

    Hi all,
    I am currently looking at a memory leak issue in the TCL UDP socket configuration when the fconfigure command is issued under a procedure.
    Under a normal scenario where the socket is configured globally, the system handles the memory well and we do not see an increase.
    The folowing examples are not the actual code implemented but provide an example of the condition under which the leak is seen.
    set msg [udp_open]
    fconfigure $msg -blocking false -buffering none -translation binary -remote [list 10.70.0.112 1234]
    proc send {} {
        global msg
        puts -nonewline $msg "HELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLO"
        return
    set done 0
    while {($done <= 1000)} {
        set done [expr {$done + 1}]
        after 250
        send
    If we wish do dynamically modify the parameters of the socket, we get an ever increasing consumption of memory (show memory dead - decrease in processor free). for example:
    set clients [list]
    lappend clients "10.70.0.111 1234"
    lappend clients "10.70.0.112 1234"
    set msg [udp_open]
    fconfigure $msg -blocking false -buffering none -translation binary
    proc send {} {
        global clients
        global msg
        foreach peer $clients {
            fconfigure $msg -remote $peer
            puts -nonewline $msg "HELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLO"
        return
    set done 0
    while {($done <= 1000)} {
        set done [expr {$done + 1}]
        after 250
        send
    I have tested multiple scenatios using flush, return, closing and opening the socket within the procedure, all to the same result - fconfigure in a procedure creates a memory leak in line with the data rate passing through the socket.
    I am seeing this across multiple device types and IOS (819,5915,5940,2901,2921,3945) 15 series M/T/GC IOS. I guess the question is, is there a problem with the construct of the procedure in which I am missing something on the channel side to release the memory or does this appear to be a bug?
    any help would be appreciated.
    Regards,
    Robert.

    Hi,
    could you please tell me the package version number you are using?
    You can obtain it by calling "package re udp".
    thx

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

  • Process memory leak issue  solaris 10

    I have a process which has a memory leak issue. I ran this process on solaris 9 as well as solaris 10. When i run prstat command i get a different output for two. Funny thing is that memory leak noted in solaris 10 is much more than that in solaris 9 e.g if it is 1 MB in solaris 9 then its 4 MB in solaris 10.
    What can be possibly causing this ? Is this related to kernel implementation on diff solaris ?

    I have a process which has a memory leak issue. I ran this process on solaris 9 as well as solaris 10. When i run prstat command i get a different output for two. Funny thing is that memory leak noted in solaris 10 is much more than that in solaris 9 e.g if it is 1 MB in solaris 9 then its 4 MB in solaris 10.
    What can be possibly causing this ? Is this related to kernel implementation on diff solaris ?

  • Memory Leak in ArrayList ?

    Dear all,
    When I went thru the implementation of ArrayList, it just appeared to me that there can be a memory leak in the ensureCapacity method, which allocated new memory... The code is as below.
    *Increases the capacity of this <tt>ArrayList</tt> instance, if*
    necessary, to ensure that it can hold at least the number of elements
    *specified by the minimum capacity argument.*
    *@param   minCapacity   the desired minimum capacity*
        public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
    *Object oldData[]* = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
                 if (newCapacity < minCapacity)
              newCapacity = minCapacity;
                // minCapacity is usually close to size, so this is a win:
                elementData = Arrays.copyOf(elementData, newCapacity);
        }Dont we need to make null the reference of oldData, as oldData = null, so that gc can reclaim the memory used by the old elementData, soon after the array copy (Arrays.copyOf) ??
    Please suggest if my understanding is wrong..
    Thanks & Regards
    Joby

    JOBY1985 wrote:
    Dear all,
    When I went thru the implementation of ArrayList, it just appeared to me that there can be a memory leak in the ensureCapacity method, which allocated new memory... The code is as below.
    *Increases the capacity of this <tt>ArrayList</tt> instance, if*
    necessary, to ensure that it can hold at least the number of elements
    *specified by the minimum capacity argument.*
    *@param   minCapacity   the desired minimum capacity*
    public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
    *Object oldData[]* = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
             if (newCapacity < minCapacity)
              newCapacity = minCapacity;
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
    }Dont we need to make null the reference of oldData, as oldData = null, so that gc can reclaim the memory used by the old elementData, soon after the array copy (Arrays.copyOf) ??No we don't need to set any thing to 'null'. The reference 'elementData' is update by the Arrays.copyOf() invocation and whatever it used to reference is then only referenced by oldData and when the block in which the reference 'oldData' is declared exits there will be no reference to the original array so it is eligible for GC.
    >
    Please suggest if my understanding is wrong..Your understanding is wrong.
    >
    Thanks & Regards
    JobyEdited by: sabre150 on Oct 20, 2009 1:20 PM

  • Memory leak in Waveform Graph?

    Either thier is a huge memory leak in the waveform graph or I am really doing something wrong.
    I created an example app with a waveform graph and a button the contructor looks as follows:
    Form1(void)
    InitializeComponent();
    vals = gcnew array<double>(60000) ;
    for (int i=0; i<60000; i++)
    vals[i]=Math:in(Math:: PI*2*60/6000.0*i) ;
    and the click event looks like this:
    System::Void button1_Click(System:: Object^ sender, System::EventArgs^ e)
    this->waveformGraph1->Plots->Clear() ;
    NationalInstruments::UI::WaveformPlot^ plot = gcnew NationalInstruments::UI::WaveformPlot(xAxis1, yAxis1) ;
    plot->PlotY(vals) ;
    plot->LineColor = Color::Red ;
    this->waveformGraph1->Plots->Add(plot) ;
    every time I click the button the memory used on my system goes up by about 10 MB.  I tried this also with using this->waveformGraph1->PlotY(vals) and the memory usage stays solid as a rock.
    Am I doing something wrong or what is causing the leak so I can work around it, my program plots 4 arrays of this size on one graph per test result.

    The plot uses some unmanaged resources (gdi objects and other handles), which is why it implements IDisposible. Because of the GC, resource cleanup is not deterministic, clean up occurs when the GC deems it necessary. Calling delete (which based on C++/CLI syntax) ultimately ends up calling Dispose and this forces the object to release any handles it might have immedietly. See the documentation for the .NET Dispose pattern for more information.
    If you don't call delete, what would end up happening is that eventually at some point in the application, the GC would fire and cleanup all the objects and handles and you would see a drop in the applications memory footprint, but you would need to run the application for a while before that might happen. In a long application run, things would end up stabilizing.
    Bilal Durrani
    NI

Maybe you are looking for