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?

Similar Messages

  • DI API objects0-memory leak

    Dear All,
    We have created a application to load AR Invoice and Incoming Payment through PowerBuilder.
    While using DI API there is a memory leak.
    ie.,After loading say 500 AR invoices and corresponding payment, the application seems to hang but after some time its processing fine.
    While adding each invoice,in the task manager the memory usage is increasing proportionally for that application.
    We found that while using DI API objects, the issue is produced.
    We are using SAP B1 2007B PL08.
    Any suggestion on this issue?

    Hi Jambulingam,
    I've seen other developers complaining about the same problem.
    Take a look at this post. It may help.
    DI Memory Leak
    Regards,
    Vítor Vieira

  • Memory Leak in multidimensional int array?

    I have a simple class
    MyMatrix.h
    @interface MyMatrix : NSObject {
    int twoDMatrix[4][4];
    int threeDMatrix[4][4][2];
    MyMatrix.m
    - init {
    twoDMatrix[0][0] = 0;
    // and so on
    twoDMatrix[3][3] = 1;
    threeDMatrix[0][0][0] = 0;
    // and so on
    threeDMatrix[3][3][1] = 1;
    // and so on
    -(void) dealloc{
    [super dealloc];
    Do you think MyMatrix class will gives Memory Leak ??

    No.

  • Memory leak - Node clean up?

    Hey guys,
    I'm running into a memory leak and was reading some other threads where people were having their own memory leaks. Is there a way through NetBeans to track memory usage or something to figure out what is consuming memory? My memory leak sounds similar to this gentleman's: [http://forums.sun.com/thread.jspa?threadID=5409788] and [http://forums.sun.com/thread.jspa?threadID=5357401]
    Setup:
    I have a mySQL database call that returns a bunch of results and in the end converts each record into its own custom node which then gets put into a sequence, which is then given to a listEventsNode (a custom node VBox) and finally put on the stage. As a note each custom node has its own animations, events, images, and shapes.
    listEventsNode gets its list of custom nodes from a publicly accessible sequence variable where its contents is simply cleared and new nodes are added by the next MySQL search. I cleared the eventSequence by using delete myCustomNodeSequence.
    I even go as far as setting the same sequence null (myCustomNodeSequence = null;). This unfortunately doesn't make any difference in terms of memory usage. java.exe will reach 100MB then crash.
    the listEventsNode is bound with eventSequence, this is to ensure that changes to the sequence of custom nodes are immediately reflected in the Vbox (listEventsNode).
    ListEventsNode is on the main stage and there is only one instance of it, but what changes is the content in the eventSequence. Even if I clear the contents of the eventSequence, it doesn't appear to "clean up" the memory.
    The way I'm doing it is probably breaking every rule in the book. I should probably make it so listEventsNode is its own object which isn't bound to any external variables (such as eventSequence) and in the event a new search takes place I simply delete the listEventsNode and when a new search is complete, it re-adds the node to the scene. Am I on the right track here?
    Is there a good "best practices" for JavaFX? For example, a typical mistake that would cause a node to "recreate" itself over and over again in memory when the programmer may have thought it was simply being "written over"? Does this make sense? Because I have a feeling that my application is not deleting the custom nodes that were created for the eventSequence and even if the eventSequence is "deleted" and re-assigned with new custom nodes, the original or previous custom nodes are still residing in memory.
    Let me know if you need to see the source or any logs/readouts from NetBeans during execution if this will help.
    Thanks for taking the time to read this.
    Cheers,
    Nik.

    Your heap usage looks pretty typical. In scenario 5, I think you are simply running out of memory. I doubt its a leak inside the javafx runtime (although it could be).+
    I think you might be right. It's running out of memory and I may have to increase the heap size.
    Say that my application legitimately needs more memory to operate, and I need to increase the heap size. How does this work if you have a fully deployed application? Is the heap size information built into the application itself so that when the jvm runs the application, it allocates the appropriate amount of memory? I've increased the heap size from 64mb to 128mb, and I added many many nodes and I still crapped out when I hit the 128mb ceiling. I changed it to 512 and I added a TON of nodes (when you click a node from the VBox, it adds a miniature version of the node to the scene graph) and I'm just under 200MB. I plan on setting a cap to how many concurrent additional nodes can be placed on the scene graph, which will help.
    If you deploy this as is, how does the application utilize memory if you've adjusted the heap size? Or is this specific to the IDE only?
    Do you know what objects are on the heap? Can you compare what objects are on the heap from one scenario to the next?+
    Where can I find this information in NetBeans profiler?
    Do you have a lot of images? Are they thumbnails or are they images scaled down to thumbnail size?+
    Actually, yes I am using a scaled down thumbnail size of the original image. The original image files are PNG format, 60x60 pixels, and about 8kb in size. I simply use the "FitWidth:" property to scale the image down. I was doing some more reading before I went to bed and I was going to use an alternative way to scale the image down. By simply doing this, the initial heap usage off the 500 node search went down form 44MB to 39MB. It's still slower on consecutive searches versus the first, but it's stable.
    Edit: I've used the width: property to downsize the image and it looks like I'm not running into that heap crash as fast but this poses a problem where I need to have the full size of the image available when a custom node is selected. What's the best way of doing this? I should probably store the image location in a string and recreate the image when I need it in full size since there is only one full size version of it on the screen at a given time. I've also completely disabled the addition of a picture in my custom node; it appears these images don't take up a lot of space since they are very small. I save an additional 3-5MB in heap space if I completely disable the pictures and have just the nodes themselves. Each node has animation effects (i.e. fading in/out of colors, changing of color if selected). Although the class itself is pretty dang long in comparison with any other classes I have.
    Are you clearing the nodes from your scene content before the search or after? If after, are you creating the new nodes before clearing out the old?+
    Yes, I have a function that reassigns the stage.scene.content sequence omitting the custom vbox that houses the list of custom nodes prior to the next search. The "cleanUp()" function is called prior to the insertion of the new custom vbox.
    It might be useful to turn on verbose garbage collection (-verbose:gc on the java command line) just to see what's happening in gc.+
    What is this exactly? I tried putting in System.gc() but I'm not sure if I'm seeing any difference yet.
    Edit: Actually, I've placed System.gc() after I run my cleanUp() function and I'm noticing the heap usage is more conservative. Seems to clear more often than it did before. But yes, the underlying problem of my running out of memory is to be looked at.
    You might also (just as an experiment) force garbage collection between your searches.+
    This seems to work well with smaller result sets. However, a search that produces over 500 custom nodes in a custom VBox uses more than half of the available heap size, so the next time it tries to do the same search it just crashes like you mentioned in your first point. The memory simply runs out. What I don't get is if I "delete" the custom vbox prior to inserting it, the memory doesn't seem to be released immediately. From what I'm reading about the garbage collector, it doesn't exactly do things in a prompt fashion.

  • Huge Memory Leak - Need help.

    Hi,
    There is a huge memory leak in our application. Because of this there are frequent session timeout. When we analysed the heap dump using Memory Analyser Tool, we got the leak suspects and the problem suspects are as below:
    One instance of "org.apache.jasper.compiler.JspRuntimeContext" loaded by "org.apache.catalina.loader.StandardClassLoader @ 0x87ff8098" occupies 161,832,200 (23.30%) bytes. The memory is accumulated in one instance of "java.util.concurrent.ConcurrentHashMap$Segment[]" loaded by "<system class loader>".
    One instance of "org.apache.catalina.tribes.tipis.LazyReplicatedMap" loaded by "org.apache.catalina.loader.StandardClassLoader @ 0x87ff8098" occupies 133,578,920 (19.23%) bytes. The memory is accumulated in one instance of "java.util.concurrent.ConcurrentHashMap$Segment[]" loaded by "<system class loader>".
    185 instances of "org.apache.jasper.runtime.BodyContentImpl", loaded by "org.apache.catalina.loader.StandardClassLoader @ 0x87ff8098" occupy 133,502,776 (19.22%) bytes.
    What could be the root cause for this error and how to resolve this?

    First, in general you not provided enough details to get any help. OS? OS version? Hardware specifics?
    Second, are you running custom code? If so, post it so you can get help.
    Third, if you're not running custom code, the odds of you having a "huge memory leak" are pretty small.

  • ADO memory leak when getting Recordset from an Oracle stored procedure?

    I am programming in C++ (VC 6) and using ADO 2.7 to
    access Oracle 9i database. My connection string looks
    like this:
    Provider=MSDAORA.1;Persist Security Info=True;User ID=scott;Password=tiger;Data Source=blahblah
    I have Oracle stored procedure that returns data in a
    REF CURSOR output parameter. Since the stored procedure
    takes input parameters, I prepare a Command object with
    Parameters initialized and attached to it. I use the
    Recordset Open method to execute the call. This approach
    works because I get correct data back from the call in
    the Recordset, but the problem is when I do this in a
    infinite loop and watch the process in Windows Taks
    Manager, I see 4k or 8k memory delta all the time and
    the Peak Memory Usage of the process keeping going up.
    I hope someone knows something in this scenario and points
    me to the right direction.
    Thanks, please see the following code for specifics.
    HRESULT CallSP3Params(VARIANT vp1, VARIANT vp2, int spretcode, LPDISPATCH ppRSet, char *pCmdLine)
         _RecordsetPtr     pRs;
         _CommandPtr     pCmd;
         _ParameterPtr     paramVProfiler[3];
         bstrt          strMissing(L"");
         *ppRSet = NULL;
         variantt          ErrConn;
         ErrConn.vt = VT_ERROR;
         ErrConn.scode = DISP_E_PARAMNOTFOUND;
         try {
         //Create instance of command object
         pCmd.CreateInstance(__uuidof(Command));
         pRs.CreateInstance(__uuidof(Recordset));
              if ( vp1.vt == VT_BSTR ) {
                   paramVProfiler[0] = pCmd->CreateParameter("P1",adVarChar,adParamInput,SysStringLen(vp1.bstrVal) + 10,strMissing );
                   paramVProfiler[0]->Value = vp1;
              else if ( vp1.vt == VT_I4 )
                   paramVProfiler[0] = pCmd->CreateParameter("P1",adNumeric,adParamInput,15,vp1);
              else
                   TESTHR( PARAMETER_OPERATION_ERROR );
              pCmd->Parameters->Append(paramVProfiler[0]);
              if ( vp2.vt == VT_BSTR ) {
                   paramVProfiler[1] = pCmd->CreateParameter("P2",adVarChar,adParamInput,SysStringLen(vp2.bstrVal) + 10,strMissing );
                   paramVProfiler[1]->Value = vp2;
              else if ( vp2.vt == VT_I4 )
                   paramVProfiler[1] = pCmd->CreateParameter("P2",adNumeric,adParamInput,15,vp2);
              else
                   TESTHR( PARAMETER_OPERATION_ERROR );
              pCmd->Parameters->Append(paramVProfiler[1]);
              paramVProfiler[2] = pCmd->CreateParameter("RETCODE",adNumeric,adParamOutput,10);
              pCmd->Parameters->Append(paramVProfiler[2]);
         //Catch COM errors
         catch( comerror &e) {
         try {
         // I manage my connection through this little C++ class of my own
         CCUsage myconnection( &Connectionkeeper[0] );
         //Set the active connection property of command object to open connection
         pCmd->ActiveConnection = myconnection.m_conn;
         //The command type is text
         pCmd->CommandType = adCmdText;
         //Set command text to call the stored procedure
         pCmd->CommandText = pCmdLine;
         //Open the Recordset to get result
         pRs->Open( variantt((IDispatch *)pCmd,true), ErrConn, adOpenStatic, adLockReadOnly, adOptionUnspecified );
         //Disconnect the command object
         pCmd->PutRefActiveConnection( NULL );
         if ( GetSPRetCode( pCmd, "RETCODE", spretcode ) != S_OK )
              TESTHR(DB_OBJECT_OPERATION_ERROR);
         // pRs->QueryInterface(IID_IDispatch, (void**) ppRSet);
         // I return the Recordset by calling QueryInterface, but even without that, closing the Recordset right here still shows memory leak.
         pRs->Close( );
         pRs = NULL;
         //Catch COM errors
    catch (_com_error e) {
         return S_OK;
    }

    Whenever large numbers of BSTRs are allocated and freed quickly the process memory will continue to climb towards a stabalizing value. BSTRs are not freed until the system frees them. You can see this by making many calls allocating and freeing BSTRs, memory will climb, but when you stop for a while the gargage collection of the sys strings will take place. I've done much research to see that a server doing many queries very rapidly is not leaking memory, but out pacing the garbage collection, it will stabilize and when the process has some "rest time" the processes memory usage will decline.
    In my research a suspected memory leak was not one.

  • Memory Leak when I get the SP return refcursor by oracle ODBC driver:

    Oracle server:&#65320;&#65328;&#65293;&#65333;&#65358;&#65353;&#65368;
    Oracle Version: 9.2.0.6.0
    Application Server: windows2003
    Develop tool &#65306; VC++;
    Question:
    when I get the return refcursor by OLEDB.Oracle, there is not any memory leak and work well. But when I change the driver to ODBC “Oralce in OraHome92"
    there will be an 56k memory leak.
    And in the other hand if I call an store precedure without return ref. Both driver /way can work well.
    Can you give me the advice? thanks a lot.
    Code such as:
    _ConnectionPtr m_AdoConnection;
    _CommandPtr pcmd = NULL;
    _RecordsetPtr sp_rs = NULL;
    _bstr_t bstrConstruct = _bstr_t("DSN=test;Uid=test;Pwd=test;PLSQLRSet=1");
    HRESULT hr = CoCreateInstance(__uuidof(Connection),NULL,CLSCTX_INPROC_SERVER,__uuidof(_ConnectionPtr),(LPVOID *)&m_AdoConnection);
    if (FAILED (hr) ) throw hr ;
    m_AdoConnection->PutCursorLocation(adUseClient) ;
    m_AdoConnection->IsolationLevel = adXactSerializable;
    m_AdoConnection->Mode = adModeShareExclusive;
    bstr_t bstrEmpty(L"") ;
    m_AdoConnection->Open (bstrConstruct, bstrEmpty, bstrEmpty, -1) ;
    SAFE_CALL(m_spObjectContext->CreateInstance(__uuidof(Command),__uuidof(_CommandPtr),(LPVOID *)&pcmd));
    if(pcmd == NULL)
    throw CAtlExceptionEx(E_POINTER,"pcmd is NULL");
    pcmd->CommandText = _bstr_t(L"wec_pkg_spl.wec_proc_spl_check");
    pcmd->CommandType = adCmdStoredProc;
    _bstr_t id = _bstr_t("65650000");     
    pcmd->Parameters->Append(pcmd->CreateParameter(_bstr_t(L"id"),DataTypeEnum(adVarChar),adParamInput,2000,_variant_t(id)));          
    pcmd->Parameters->Append(pcmd->CreateParameter(_bstr_t(L"errcode"),DataTypeEnum(adNumeric),adParamOutput,4));
    pcmd->Parameters->Append(pcmd->CreateParameter(_bstr_t(L"errdescription"),DataTypeEnum(adVarChar),adParamOutput,2000));
    pcmd->ActiveConnection = sp_con.m_AdoConnection;
    sp_rs = pcmd->Execute(NULL,NULL,adCmdStoredProc);
    pcmd->Release;          
    sp_rs->Close();     
    if (m_AdoConnection->State == adStateOpen)
    m_AdoConnection->Close();
    wec_pkg_spl.wec_proc_spl_check arguments:
    id          varchar2     in
    flowpaths     ref cursor     out
    errcode          number          out
    errdescription     varchar2     out
    Message was edited by:
    [email protected]

    I'm using the oracle ODBC driver 8.05.10 with MFC and client version 8.0.5. In my experience you can't prevent memory leaks with that or earlier versions of the ODBC driver. Client patchkits or service packs for NT or the Visual Studio doesn't solve the problem.
    The following code will result in a memory leak with the oracle driver. With every expiration of the timer the leak will grow.
    void CTestOdbcOracleDriverDlg::OnTimer(UINT nIDEvent)
    TCHAR errString[255];
    //open the database with class CDatabase
    //use of CRecordset
    TRY {
    //my table name is AL_ALARME_LOG
    pMyRecordset->Open(CRecordset::dynaset,"SELECT * FROM AL_ALARME_LOG",CRecordset::none);
    //do something with the data
    Sleep(0);
    pMyRecordset->Close();
    CATCH_ALL(error) {
    error->GetErrorMessage(errString,255);
    DELETE_EXCEPTION(error);
    END_CATCH_ALL
    CDialog::OnTimer(nIDEvent);
    The same code with the Microsoft ODBC driver
    doesn't cause memory leaks.
    Andreas ([email protected])

  • Calling SetLocalTime in C# causes Memory Leak (WEC7)

    Hello,
    I use SetLocalTime() in C#. Everything works well if I start explorer.exe and my application. But if I don't start explorer.exe at system start. SetLocalTime() causes memory leak in my application. I call the function frequently every hour.
    public static bool SetzeLokalZeit(SYSTEMDATETIME lpSystemTime)
    #if DEADLOCKDETECT
    using (DdMonitor.Lock(MyTimeLock, "MyTimeLock#1"))
    #else
    lock (MyTimeLock)
    #endif
    bool ret = false; // no Success
    try
    GLB.LogFile.MyWrite("SetLocalTime");
    SYSTEMDATETIME loc = new SYSTEMDATETIME();
    loc.wYear = lpSystemTime.wYear;
    loc.wMonth = lpSystemTime.wMonth;
    loc.wDayOfWeek = lpSystemTime.wDayOfWeek;
    loc.wDay = lpSystemTime.wDay;
    loc.wHour = lpSystemTime.wHour;
    loc.wMinute = lpSystemTime.wMinute;
    loc.wSecond = lpSystemTime.wSecond;
    loc.wMilliseconds = lpSystemTime.wMilliseconds;
    ret = SetLocalTime(ref loc);
    if (!ret) // no Success
    int err = Marshal.GetLastWin32Error();
    if (err > 0)
    GLB.LogFile.MyWrite("ERROR CODE:" + err.ToString());
    else ret = true;
    catch (Exception ex)
    GLB.LogFile.MyWrite("000023 Exception" + ex.Message);
    finally
    GLB.LogFile.MyWrite("SetLocalTime Ende");
    return ret;
    Has someone an idea what's the problem?
    Best regards,
    Andreas

    Hello,
    Here the answers to the questions:
    1. Does the SetLocalTime function succeed?
    Calling SetLocalTime doesn't cause an exception an the local time is set correctly.
    2. Do you still get the memory leak if you remove all other calls?
    Yes. I have removed any other code, but I also get the memory leak.
    3. Does the memory leak also occur when you do this from native code?
    I have not tried it yet. But I will still make it...
    [DllImport("coredll.dll")]
    private static extern void GetLocalTime(ref SYSTEMDATETIME lpSystemTime);
    [DllImport("coredll.dll", SetLastError = true)]
    private static extern bool SetLocalTime(ref SYSTEMDATETIME lpSystemTime);
    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEMDATETIME
    public ushort wYear;
    public ushort wMonth;
    public ushort wDayOfWeek;
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMilliseconds;
    public static bool Pub_SetLocalTime(SYSTEMDATETIME lpSystemTime)
    lock (MyTimeLock)
    bool ret = false; // no Success
    try
    loc_set.wYear = lpSystemTime.wYear;
    loc_set.wMonth = lpSystemTime.wMonth;
    loc_set.wDayOfWeek = lpSystemTime.wDayOfWeek;
    loc_set.wDay = lpSystemTime.wDay;
    loc_set.wHour = lpSystemTime.wHour;
    loc_set.wMinute = lpSystemTime.wMinute;
    loc_set.wSecond = lpSystemTime.wSecond;
    loc_set.wMilliseconds = lpSystemTime.wMilliseconds;
    ret = SetLocalTime(ref loc_set);
    if (!ret) // no Success
    int err = Marshal.GetLastWin32Error();
    if (err > 0)
    MessageBox.Show("Win32 Error:", err.ToString());
    else ret = true;
    catch (Exception ex)
    MessageBox.Show("SetLocalTime,Exception:", ex.ToString());
    finally
    return ret;
    Best regards,
    Andreas

  • Safari + Javascript = Slowdown and Memory Leak?

    I've pinned down what I think is some problem with Safari and Javascript.
    If I leave Safari open for over 24 hours, with several pages open in tabs, in Activity Monitor Safari shows about 1.38Gig of VM and Safari is molasses slow.
    Turning off Javascript immediately restores the speed in Safari but the HUGE VM usage remains.
    So, I turned off Javascript, relaunched Safari, opened the exact same sites in tabs and left Safari sitting there for 24+ hours. It's now using only 203MBs of VM and it's still swishy fast as it should be.
    It seems like a problem between Safari and Javascript. Can anyone else confirm this phenomena before I send an official report to Apple?
    Thanks:)

    Confirmed. Running Safari with the Debug option on will tell you that there are some memory leaks with JavaScript objects.

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

  • Custom MediaStreamSource and Memory Leaks During SampleRequested

    Greetings,
    I have a nasty memory leak problem that is causing me to pull my hair out.
    I'm implementing a custom MediaStreamSource along with MediaTranscoder to generate video to disk. The frame generation operation occurs in the SampleRequested handler (as in the MediaStreamSource example). No matter what I do - and I've tried a
    ton of options - inevitably the app runs out of memory after a couple hundred frames of HD video. Investigating, I see that indeed GC.GetTotalMemory reports an increasing, and never decreasing, amount of allocated RAM. 
    The frame generator in my actual app is using RenderTargetBitmap to get screen captures, and is handing the buffer to MediaStreamSample.CreateFromBuffer(). However, as you can see in the example below, the issue occurs even with a dumb allocation
    of RAM and no other actual logic. Here's the code:
    void _mss_SampleRequested(Windows.Media.Core.MediaStreamSource sender, MediaStreamSourceSampleRequestedEventArgs args)
    if ( args.Request.StreamDescriptor is VideoStreamDescriptor )
    if (_FrameCount >= 3000) return;
    var videoDeferral = args.Request.GetDeferral();
    var descriptor = (VideoStreamDescriptor)args.Request.StreamDescriptor;
    uint frameWidth = descriptor.EncodingProperties.Width;
    uint frameHeight = descriptor.EncodingProperties.Height;
    uint size = frameWidth * frameHeight * 4;
    byte[] buffer = null;
    try
    buffer = new byte[size];
    // do something to create the frame
    catch
    App.LogAction("Ran out of memory", this);
    return;
    args.Request.Sample = MediaStreamSample.CreateFromBuffer(buffer.AsBuffer(), TimeFromFrame(_FrameCount++, _frameSource.Framerate));
    args.Request.Sample.Duration = TimeFromFrame(1, _frameSource.Framerate);
    buffer = null; // attempt to release the memory
    videoDeferral.Complete();
    App.LogAction("Completed Video frame " + (_FrameCount-1).ToString() + "\n" +
    "Allocated memory: " + GC.GetTotalMemory(true), this);
    return;
    It usually fails around frame 357, with GC.GetTotalMemory() reporting 750MB allocated.
    I've tried tons of work-arounds, none of which made a difference. I tried putting the code that allocates the bytes in a separate thread - no dice.  I tried Task.Delay to give the GC a chance to work, on the assumption that it just had no time
    to do its job. No luck.
    As another experiment, I wanted to see if the problem went away if I allocated memory each frame, but never assigned it to the MediaStreamSample, instead giving the sample (constant) dummy data. Indeed, in that scenario, memory consumption stayed
    constant. However, while I never get an out-of-memory exception, RequestSample just stops getting called around frame 1600 and as a result the transcode operation never actually returns to completion.
    I also tried taking a cue from the SDK sample which uses C++ entirely to generate the frame. So I passed the buffer as a Platform::Array<BYTE> to a static Runtime extension class function I wrote in C++.
    I won't bore you with the C++ code, but even directly copying the bytes of the array to the media sample using memcpy still had the same result! It seems that there is no way to communicate the contents of the byte[] array to the media sample without
    it never being released.
    I know what some will say: the difference between my code and the SDK sample, of course, is that the SDK sample generates the frame _entirely_ in C++, thus taking care of its own memory allocation and deallocation. Because I want to get
    the data from RenderTargetBitmap, this isn't an option for me. (As a side note, if anyone knows if there's a way to get the contents of an RT Window using DirectX, that might work too, but I know this is not a C++ forum, so...). But more importantly,
    MediaStreamSource and MediaStreamSample are managed classes that appear to allow you to generate custom frames using C# or other managed code. The MediaStreamSample.CreateFromBuffer function appears to be tailored for exactly what I want. But there appears
    to be no way to release the buffer when giving the bytes to the MediaStreamSample. At least none that I can find.
    I know the RT version of these classes are new to Windows 8.1, but I did see other posts going back 3 years discussing a similar issue in Silverlight. That never appears to have been resolved.
    I guess the question boils down to this: how do I safely get managed data, allocated during the SampleRequested handler, to the MediaStreamSample without causing a memory leak? Also, why would the SampleRequested handler just stop getting called
    out of the blue, even when I artificially eliminate the memory leak problem?
    Thanks so much for all input!

    Hi Rob - 
    Thanks for your quick reply and for clarifying the terminology. 
    In the Memory Usage test under Analyze/Performance and Diagnostics (is that what you mean?) it's clear that each frame of video being created is not released from memory except when memory consumption gets very high. GC will occasionally kick in, but eventually
    it succumbs.
    Interestingly, if I reduce the frame size substantially, say 320x240, it never runs out of RAM no matter how many frames I throw at it. The Memory Usage test, however, shows the same pattern. But this time the GC can keep up and release the RAM.
    After playing with this ad nauseum,  I am fairly convinced I know what the problem is, but the solution still escapes me. It appears that the Transcoder is requesting frames from the MediaStreamSource (and the MediaStreamSource is providing them via
    my SampleRequested handler) faster than the Transcoder can write them to disk and release them. Why would this be happening? The MediaStreamSource.BufferTime property is - I thought - used to prevent this very problem. However, changing the BufferTime seems
    to have no effect at all - even changing it to ZERO doesn't change anything. If I'm right, this would explain why the GC can't do its job - it can't release the buffers I'm giving to the Transcoder via SampleRequested because the Transcoder won't give them
    up until it's finished transcoding and writing them to disk. And yet the transcoder keeps requesting samples until there's no more memory to create them with.
    The following code, which I made from scratch to illustrate my scenario, should be air-tight according to everything I've read. And yet, it still runs out of memory when the frame size is too large. 
    If you or anyone else can spot the problem in this code, I'd be thrilled to hear it. Maybe I'm omitting a key step with regard to getting the deferral? Or maybe it's a bug in the back-end? Can I "slow down" the transcoder and force it to release samples
    it's already used?
    Anyway here's the new code, which other than App.cs is everything. So if I'm doing something wrong it will be in this module:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Diagnostics;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.UI.Popups;
    using Windows.Storage;
    using Windows.Storage.Pickers;
    using Windows.Storage.Streams;
    using Windows.Media.MediaProperties;
    using Windows.Media.Core;
    using Windows.Media.Transcoding;
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    namespace MyTranscodeTest
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    MediaTranscoder _transcoder;
    MediaStreamSource _mss;
    VideoStreamDescriptor _videoSourceDescriptor;
    const int c_width = 1920;
    const int c_height = 1080;
    const int c_frames = 10000;
    const int c_frNumerator = 30000;
    const int c_frDenominator = 1001;
    uint _frameSizeBytes;
    uint _frameDurationTicks;
    uint _transcodePositionTicks = 0;
    uint _frameCurrent = 0;
    Random _random = new Random();
    public MainPage()
    this.InitializeComponent();
    private async void GoButtonClicked(object sender, RoutedEventArgs e)
    Windows.Storage.Pickers.FileSavePicker picker = new Windows.Storage.Pickers.FileSavePicker();
    picker.FileTypeChoices.Add("MP4 File", new List<string>() { ".MP4" });
    Windows.Storage.StorageFile file = await picker.PickSaveFileAsync();
    if (file == null) return;
    Stream outputStream = await file.OpenStreamForWriteAsync();
    var transcodeTask = (await this.InitializeTranscoderAsync(outputStream)).TranscodeAsync();
    transcodeTask.Progress = (asyncInfo, progressInfo) =>
    Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    _ProgressReport.Text = "Sourcing frame " + _frameCurrent.ToString() + " of " + c_frames.ToString() +
    " with " + GC.GetTotalMemory(false).ToString() + " bytes allocated.";
    await transcodeTask;
    MessageDialog dialog = new MessageDialog("Transcode completed.");
    await dialog.ShowAsync();
    async Task<PrepareTranscodeResult> InitializeTranscoderAsync (Stream output)
    _transcoder = new MediaTranscoder();
    _transcoder.HardwareAccelerationEnabled = false;
    _videoSourceDescriptor = new VideoStreamDescriptor(VideoEncodingProperties.CreateUncompressed( MediaEncodingSubtypes.Bgra8, c_width, c_height ));
    _videoSourceDescriptor.EncodingProperties.PixelAspectRatio.Numerator = 1;
    _videoSourceDescriptor.EncodingProperties.PixelAspectRatio.Denominator = 1;
    _videoSourceDescriptor.EncodingProperties.FrameRate.Numerator = c_frNumerator;
    _videoSourceDescriptor.EncodingProperties.FrameRate.Denominator = c_frDenominator;
    _videoSourceDescriptor.EncodingProperties.Bitrate = (uint)((c_width * c_height * 4 * 8 * (ulong)c_frDenominator) / (ulong)c_frNumerator);
    _frameDurationTicks = (uint)(10000000 * (ulong)c_frDenominator / (ulong)c_frNumerator);
    _frameSizeBytes = c_width * c_height * 4;
    _mss = new MediaStreamSource(_videoSourceDescriptor);
    _mss.BufferTime = TimeSpan.FromTicks(_frameDurationTicks);
    _mss.Duration = TimeSpan.FromTicks( _frameDurationTicks * c_frames );
    _mss.Starting += _mss_Starting;
    _mss.Paused += _mss_Paused;
    _mss.SampleRequested += _mss_SampleRequested;
    MediaEncodingProfile outputProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Ntsc);
    outputProfile.Audio = null;
    return await _transcoder.PrepareMediaStreamSourceTranscodeAsync(_mss, output.AsRandomAccessStream(), outputProfile);
    void _mss_Paused(MediaStreamSource sender, object args)
    throw new NotImplementedException();
    void _mss_Starting(MediaStreamSource sender, MediaStreamSourceStartingEventArgs args)
    args.Request.SetActualStartPosition(new TimeSpan(0));
    /// <summary>
    /// This is derived from the sample in "Windows 8.1 Apps with Xaml and C# Unleashed"
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    void _mss_SampleRequested(MediaStreamSource sender, MediaStreamSourceSampleRequestedEventArgs args)
    if (_frameCurrent == c_frames) return;
    var deferral = args.Request.GetDeferral();
    byte[] frameBuffer;
    try
    frameBuffer = new byte[_frameSizeBytes];
    this._random.NextBytes(frameBuffer);
    catch
    throw new Exception("Sample source ran out of RAM");
    args.Request.Sample = MediaStreamSample.CreateFromBuffer(frameBuffer.AsBuffer(), TimeSpan.FromTicks(_transcodePositionTicks));
    args.Request.Sample.Duration = TimeSpan.FromTicks(_frameDurationTicks);
    args.Request.Sample.KeyFrame = true;
    _transcodePositionTicks += _frameDurationTicks;
    _frameCurrent++;
    deferral.Complete();
    Again, I can't see any reason why this shouldn't work. You'll note it mirrors pretty closely the sample in the Windows 8.1 Apps With Xaml Unleashed book (Chapter 14). The difference is I'm feeding the samples to a transcoder rather than a MediaElement (which,
    again should be no issue).
    Thanks again for any suggestions!
    Peter

  • Memory leak in Servlet Filter handling?

    In Sun Web Server 6.1, I'm finding a memory leak when using servlet filters. I've even created a "no op" servlet filter. When it's registered, every 10000 hits or so to filtered static content will eat up about 5 to 10 MB of RAM. The JVM heap size doesn't increase.
    When I remove the filter, I've hit the same static page on the server 50000 times without seeing an increase in memory usage by the process.
    This is on Windows 2000, and I think the Sun Web Server 6.1 is SP1. I haven't tried SP2 yet.
    For reference, here's the filter I put in:
    public class NoOpFilter implements Filter
    public void init(FilterConfig arg0) throws ServletException {}
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    chain.doFilter(request, response);
    public void destroy() {}
    }

    I found the bug. I get the memory leak if magnus.conf has either or both of the following entries:
    AdminLanguage en
    DefaultLanguage en
    If I delete the entries, the memory leak goes away. I suppose this should get fixed by Sun sometime. Maybe I'll figure out how to officially report the bug later.

  • Possible of memory leak in the loop

    Recently my application do get OutOfMemory issue. I realized the memory is keep on stack up as i saw in the task manager, the jlaunch keep growing and it won't drop back. That day i'm running a search function and it will query the table to retrieve the data. The jlaunch shoot from 500MB -> 2.2GB and now remain in there. Wondering is it during it query it populate at least 10,000 records into the arraylist and then the memory already allocated and once i finish run the function, it will clear the allocated memory to re-use it.
    public ArrayList ejbHomeInJDBCConnection(Map map){
         ArrayList beanList = new ArrayList();
         try{
              Context ctx = new InitialContext();
              DataSource ds = (DataSource) ctx.lookup("jdbc/POOL");
              Connection con = ds.getConnection();
              String query = "SELECT * FROM USER WHERE ";
              for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                   Object key = iterator.next();
                   if(key.toString().startsWith("TIME") | key.toString().startsWith("TIMEIN")){
                        long longValue = Long.parseLong(map.get(key).toString());
                        query += key.toString()+ longValue + " AND ";      
                   }else{
                        String value = (String)map.get(key);
                        query += key.toString()+ value + " AND ";      
              String newquery = query.substring(0, query.length()-5);
              newquery += " ORDER BY TIMEIN DESC";
              Statement stmt = con.createStatement();
              try {
                   ResultSet rs = stmt.executeQuery(newquery);
                  try {
                        while (rs.next()){
                             InBean bean = new InBean();
                             bean.setSmsId(rs.getString("EMP"));
                             beanList.add(bean);
                   }finally{
                        rs.close();
              }finally{
                   stmt.close();
         }catch(Exception e){
              System.err.println(e.fillInStackTrace());
    return beanList;
    Wondering is it the InBean will cause any memory leak as if there is 10,000 records, which mean it will create 10,000 objects and once it add into the arraylist the previous bean is not in use, will the GC clear it as i didn't set it as null. Do i need to do something like reallocate/defragment the memory?
    Thanks.

    Hi,
    I'm sure a "count" would not generate the overhead you are concerned.
    To understand some aspects, you need to read the source files of Java, and understand how the stack would work in your case.
    Evertime you "add" an element to you list, the implementation will run the ensureCapacity, and grown the list one by one. Understand that the list is an Array with a lot more functions, but below, you are still working with an Array, and it needs to have a defined size. Everytime you add, it's doing a System.arraycopy(all the crap) - So you can save this, everytime you add something if you create your List with the right size.
    Note, this is not an issue if we consider small lists, of small objects, but working with large lists, you can feel slow downs.
    About the GC stuff, well.. I'm sure you can do some reading how it works. One good start point would be
    Link: [http://java.sun.com/docs/hotspot/gc1.4.2/]
    I'm sure you don't need that, but still, it's good reading. Maybe you should just increase your heap size, or you can manually clear the List using list.clear();
    Rgds,
    Daniel

  • Potential Memory Leak during Marshelling of a Web Service Response

    I believe I have found a memory leak when using the configuration below.
    The memory leak occurs when calling a web service. When the web service function is marshelling the response of the function call, an "500 Internal Server Error ... java.lang.OutOfMemoryError" is returned from OC4J. This error may be seen via the TCP Packet Monitor in JDeveloper.
    Unfortunately no exception dump is outputted to the OC4J log.
    Configuration:
    Windows 2000 with 1 gig ram
    JDeveloper 9.0.5.2 with JAX/RPC extension installed
    OC4J 10.0.3
    Sun JVM version 1.4.2_03-b02
    To demonstrate the error I created a simple web service and client. See below the client and web service function that demonstrates it.
    The web service is made up of a single function called "queryTestOutput".
    It returns an object of class "TestOutputQueryResult" which contains an int and an array.
    The function call accepts a one int input parameter which is used to vary the size of array in the returned object.
    For small int (less than 100). Web service function returns successfully.
    For larger int and depending on the size of memory configuration when OC4J is launched,
    the OutOfMemoryError is returned.
    The package "ws_issue.service" contains the web service.
    I used the Generate JAX-RPC proxy to build the client (found in package "ws_issue.client"). Package "types" was
    also created by Generate JAX-RPC proxy.
    To test the web service call execute the class runClient. Vary the int "atestValue" until error is returned.
    I have tried this with all three encodings: RPC/Encoded, RPC/Literal, Document/Literal. They have the
    same issue.
    The OutOfMemory Error is raised fairly consistently using the java settings -Xms386m -Xmx386m for OC4J when 750 is specified for the input parameter.
    I also noticed that when 600 is specified, the client seems to hang. According to the TCP Packet Monitor,
    the response is returned. But, the client seems unable to unmarshal the message.
    ** file runClient.java
    // -- this client is using Document/Literal
    package ws_issue.client;
    public class runClient
    public runClient()
    * @param args
    * Test out the web service
    * Play with the atestValue variable to until exception
    public static void main(String[] args)
    //runClient runClient = new runClient();
    long startTime;
    int atestValue = 1;
    atestValue = 2;
    //atestValue = 105; // last one to work with default memory settings in oc4j
    //atestValue = 106; // out of memory error as seen in TCP Packet Monitor
    // fails with default memory settings in oc4j
    //atestValue = 600; // hangs client (TCP Packet Monitor shows response)
    // when oc4j memory sessions are -Xms386m -Xmx386m
    atestValue = 750; // out of memory error as seen in TCP Packet Monitor
    // when oc4j memory sessions are -Xms386m -Xmx386m
    try
    startTime = System.currentTimeMillis();
    Ws_issueInterface ws = (Ws_issueInterface) (new Ws_issue_Impl().getWs_issueInterfacePort());
    System.out.println("Time to obtain port: " + (System.currentTimeMillis() - startTime) );
    // call the web service function
    startTime = System.currentTimeMillis();
    types.QueryTestOutputResponse qr = ws.queryTestOutput(new types.QueryTestOutput(atestValue));
    System.out.println("Time to call queryTestOutput: " + (System.currentTimeMillis() - startTime) );
    startTime = System.currentTimeMillis();
    types.TestOutputQueryResult r = qr.getResult();
    System.out.println("Time to call getresult: " + (System.currentTimeMillis() - startTime) );
    System.out.println("records returned: " + r.getRecordsReturned());
    for (int i = 0; i<atestValue; i++)
    types.TestOutput t = r.getTestOutputResults();
    System.out.println(t.getTestGroup() + ", " + t.getUnitNumber());
    catch (Exception e)
    e.printStackTrace();
    ** file wsmain.java
    package ws_issue.service;
    import java.rmi.RemoteException;
    import javax.xml.rpc.ServiceException;
    import javax.xml.rpc.server.ServiceLifecycle;
    public class wsmain implements ServiceLifecycle, ws_issueInterface
    public wsmain()
    public void init (Object p0) throws ServiceException
    public void destroy ()
    System.out.println("inside ws destroy");
    * create an element of the array with some hardcoded values
    private TestOutput createTestOutput(int cnt)
    TestOutput t = new TestOutput();
    t.setComments("here are some comments");
    t.setConfigRevisionNo("1");
    t.setItemNumber("123123123");
    t.setItemRevision("arev" + cnt);
    t.setTestGroup(cnt);
    t.setTestedItemNumber("123123123");
    t.setTestedItemRevision("arev" + cnt);
    t.setTestResult("testResult");
    t.setSoftwareVersion("version");
    t.setTestConditions("conditions");
    t.setStageName("world's a stage");
    t.setTestMode("Test");
    t.setTestName("test name");
    t.setUnitNumber("UnitNumber"+cnt);
    return t;
    * Web service function that is called
    * Create recCnt number of "records" to be returned
    public TestOutputQueryResult queryTestOutput (int recCnt) throws java.rmi.RemoteException
    System.out.println("Inside web service function queryTestOutput");
    TestOutputQueryResult r = new TestOutputQueryResult();
    TestOutput TOArray[] = new TestOutput[recCnt];
    for (int i = 0; i< recCnt; i++)
    TOArray[i] = createTestOutput(i);
    r.setRecordsReturned(recCnt);
    r.setTestOutputResults(TOArray);
    System.out.println("End of web service function call");
    return r;
    * @param args
    public static void main(String[] args)
    wsmain wsmain = new wsmain();
    int aval = 5;
    try
    TestOutputQueryResult r = wsmain.queryTestOutput(aval);
    for (int i = 0; i<aval; i++)
    TestOutput t = r.getTestOutputResults()[i];
    System.out.println(t.getTestGroup() + ", " + t.getUnitNumber());
    catch (Exception e)
    e.printStackTrace();
    ** file ws_issueInterface.java
    package ws_issue.service;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface ws_issueInterface extends java.rmi.Remote
    public TestOutputQueryResult queryTestOutput (int recCnt) throws java.rmi.RemoteException;
    ** file TestOutputQueryResult.java
    package ws_issue.service;
    public class TestOutputQueryResult
    private long recordsReturned;
    private TestOutput[] testOutputResults;
    public TestOutputQueryResult()
    public long getRecordsReturned()
    return recordsReturned;
    public void setRecordsReturned(long recordsReturned)
    this.recordsReturned = recordsReturned;
    public TestOutput[] getTestOutputResults()
    return testOutputResults;
    public void setTestOutputResults(TestOutput[] testOutputResults)
    this.testOutputResults = testOutputResults;
    ** file TestOutput.java
    package ws_issue.service;
    public class TestOutput
    private String itemNumber;
    private String itemRevision;
    private String configRevisionNo;
    private String testName;
    private String testConditions;
    private String stageName;
    private String testedItemNumber;
    private String testedItemRevision;
    private String unitNumber;
    private String testStation;
    private String testResult;
    private String softwareVersion;
    private String operatorID;
    private String testDate; // to be datetime
    private String comments;
    private int testGroup;
    private String testMode;
    public TestOutput()
    public String getComments()
    return comments;
    public void setComments(String comments)
    this.comments = comments;
    public String getConfigRevisionNo()
    return configRevisionNo;
    public void setConfigRevisionNo(String configRevisionNo)
    this.configRevisionNo = configRevisionNo;
    public String getItemNumber()
    return itemNumber;
    public void setItemNumber(String itemNumber)
    this.itemNumber = itemNumber;
    public String getItemRevision()
    return itemRevision;
    public void setItemRevision(String itemRevision)
    this.itemRevision = itemRevision;
    public String getOperatorID()
    return operatorID;
    public void setOperatorID(String operatorID)
    this.operatorID = operatorID;
    public String getSoftwareVersion()
    return softwareVersion;
    public void setSoftwareVersion(String softwareVersion)
    this.softwareVersion = softwareVersion;
    public String getStageName()
    return stageName;
    public void setStageName(String stageName)
    this.stageName = stageName;
    public String getTestConditions()
    return testConditions;
    public void setTestConditions(String testConditions)
    this.testConditions = testConditions;
    public String getTestDate()
    return testDate;
    public void setTestDate(String testDate)
    this.testDate = testDate;
    public String getTestName()
    return testName;
    public void setTestName(String testName)
    this.testName = testName;
    public String getTestResult()
    return testResult;
    public void setTestResult(String testResult)
    this.testResult = testResult;
    public String getTestStation()
    return testStation;
    public void setTestStation(String testStation)
    this.testStation = testStation;
    public String getTestedItemNumber()
    return testedItemNumber;
    public void setTestedItemNumber(String testedItemNumber)
    this.testedItemNumber = testedItemNumber;
    public String getTestedItemRevision()
    return testedItemRevision;
    public void setTestedItemRevision(String testedItemRevision)
    this.testedItemRevision = testedItemRevision;
    public String getUnitNumber()
    return unitNumber;
    public void setUnitNumber(String unitNumber)
    this.unitNumber = unitNumber;
    public int getTestGroup()
    return testGroup;
    public void setTestGroup(int testGroup)
    this.testGroup = testGroup;
    public String getTestMode()
    return testMode;
    public void setTestMode(String testMode)
    this.testMode = testMode;

    I use web services a lot and I sympathize with your issue. I
    struggle with similar issues and I found this great utility that
    will help you confirm if your webservice is returning the data
    correctly to Flex. I know you said it works in other applications
    but who knows if flex is calling it correctly etc. This utility is
    been the most amazing tool in helping me resolve web service
    issues.
    http://www.charlesproxy.com/
    Once you can confirm the data being returned is good you can
    try several things in flex. Try changing your result format to
    object or e4x etc. See how that plays out. Not sure where your
    tapping in to look at your debugger, you might want to catch it
    right at the result handler before converting to any collections. .
    If nothing here helps maybe post some code to look at. .
    .

Maybe you are looking for

  • Email PDF from Mail Merge Problem

    Using a data source of email addresses from Excel 2003 and performing a mail merge in Word 2003 with the Mail Merge to Adobe PDF button, everything worked okay and the emails generated to the outbox in Outlook 2003 with the relevant PDFs attached.  H

  • Is it still possible to obtain imovie HD?

    Friends, I have ilife 08 but I would like to obtain a version of imovie HD. Is it possible? I can't find a downloadable version on Apple's website. Thanks! Steve

  • Applying a patch to OBIEE 11g

    Hello Everyone, I am new to OBI and specially new to 11g, Now most of you guys will know that there was a bug in 11g in which if you want to see the query generated by the report in session log, It shows "no log found". Now there was a patch availabl

  • Questions about Novation Remote 25SL integration with Logic Pro 8

    Preface: I have to apologize in advance if this seems somewhat confusing. I'm sure some of the terms I'm using are just plain wrong - I'm somewhat of a n00b. I have a Novation Remote 25SL configured to use AutoMap with Logic Pro 8 from Novation's web

  • How to call webservice from OAF

    Hi, I need to call a webservice in one of my custom OAF page. I am very new to OAF and Java and have no idea about how webservice works. Does anybody has any example of that, are there any setups I need to perform. I will appreciate if someone can sh