Memory leak in Callable Statement

We are using Weblogic 6.1 and Oracle 8.1.7 for an application we are developing.
Usage of callable statement seems to be resulting an a memory leak. The program runs
in a loop and after processing 200 records, java.lang.outofMemory Exception is thrown
We are unable to figure out a reason for the same.
The code snippet is as below
try
//dbConn = ImportPODBConnect.getDBConnection(dsJNDIName, dsURL); //connect
to DB <br>
dbConn = DBConnect.getDBConnection(dsJNDIName, dsURL);
//query = POQueries.selectPO(poId); //get the required
query statement from the POQueries utility class
                         Print.log(" in getPO() ----> ********* before 1st stmt " + System.currentTimeMillis());
                    cstmt = dbConn.prepareCall("{ ? = call PO_HEADER_PROC(?)}");
                    cstmt.registerOutParameter(1, OracleTypes.CURSOR);
               cstmt.setFloat(2, poId);
               // execute and retrieve the result set
               cstmt.execute();
               getPORs = (ResultSet)cstmt.getObject(1);
                         Print.log(" in getPO() ----> ********* after 1st stmt " + System.currentTimeMillis());
                         if (!getPORs.next()) //if nothing returned then
throw an exception
                              Print.log("Unable to get the required PO:" + poId);
                              throw new Exception("Unable to get the required PO:" + poId);
                         else //set all the variables
of the PO header objects from the result set
                              pohSl = new POHeaderSl();
                              pohSl.setOvUserName(getPORs.getString("OVA_USER_NAME"));
                              pohSl.setOvCompanyName(getPORs.getString("OVA_COMPANY_NAME"));
                              pohSl.setAgent(getPORs.getString("AGENT"));
                              pohSl.setApprovalCode(getPORs.getString("APPROVAL_CODE"));
                              pohSl.setBrand(getPORs.getString("BRAND"));
                              pohSl.setBusinessSegment(getPORs.getString("BUSINESS_SEGMENT"));
                              pohSl.setBusinessSubSegment(getPORs.getString("BUSINESS_SUB_SEGMENT"));
                              pohSl.setBuyDate(getPORs.getString("BUY_DATE"));
                              pohSl.setCareContentLabel(getPORs.getString("CARE_CONTENT_LABEL"));
                              pohSl.setCartonMarkings1(getPORs.getString("CARTON_MARKINGS_1"));
                              pohSl.setCartonMarkings2(getPORs.getString("CARTON_MARKINGS_2"));
                              pohSl.setCartonMarkings3(getPORs.getString("CARTON_MARKINGS_3"));
                              pohSl.setCartonMarkings4(getPORs.getString("CARTON_MARKINGS_4"));
                              pohSl.setComments(getPORs.getString("COMMENTS"));
                              pohSl.setCommissionPerUnit(getPORs.getString("COMMISSION_PER_UNIT"));
                              pohSl.setCompanyId(getPORs.getString("COMPANY_ID"));
                              pohSl.setCompulsoryString(getPORs.getString("COMPULSORY_STRING"));
                              pohSl.setConTimestamp(getPORs.getString("CON_TIMESTAMP"));
                              pohSl.setCurrency(getPORs.getString("CURRENCY"));
                              pohSl.setCustomerBillToNumber(getPORs.getString("CUSTOMER_BILL_TO_NUMBER"));
                              pohSl.setCustomerLcBank(getPORs.getString("CUSTOMER_LC_BANK"));;
                              pohSl.setCustomerLcDate(getPORs.getString("CUSTOMER_LC_DATE"));
                              pohSl.setCustomerLcExpiryDate(getPORs.getString("CUSTOMER_LC_EXPIRY_DATE"));
                              pohSl.setCustomerLcNumber(getPORs.getString("CUSTOMER_LC_NUMBER"));
                              pohSl.setCustomerPoNumber(getPORs.getString("CUSTOMER_PO_NUMBER"));
                              pohSl.setCustomerSaleDept(getPORs.getString("CUSTOMER_SALE_DEPT"));
                              pohSl.setCustomerShipToNumber(getPORs.getString("CUSTOMER_SHIP_TO_NUMBER"));
                              pohSl.setCustomerSo(getPORs.getString("CUSTOMER_SO"));
                              pohSl.setDateLastModifiedErp(getPORs.getString("DATE_LAST_MODIFIED_ERP"));
                              pohSl.setDateLastModifiedOv(getPORs.getString("DATE_LAST_MODIFIED_OV"));
                              pohSl.setDateOfActivation(getPORs.getString("DATE_OF_ACTIVATION"));
                              Print.log(" ******** inside getPO() ----- > ****** built Header" + System.currentTimeMillis()
                              if(getPORs != null)
                                   getPORs.close();
                                   getPORs = null;
                              if(cstmt != null)
                                   Print.log("In the close");
                                   cstmt.close();
                                   cstmt = null;
                    catch (Exception e)
                         System.out.println(" in dataAccess.getPO() ----- > " + e.toString());
                         throw new Exception(e.toString()); //if there are any exceptions
then throw back the exceptions
                    finally //finally block to release any connections
and statement objects
                         if(getPORs != null)
                              getPORs.close();
                              getPORs = null;
                         if (pstmt!=null)
                              pstmt.close();
                              pstmt = null;
                         if (cstmt!=null)
                              cstmt.close();
                              cstmt = null;
                         if (dbConn!=null)
                              dbConn.close();
                              dbConn = null;
                    return poSl; //return the PO object
Can anyone help with this?

hi
This may happen when you open resultset objects and not close them properly.
Try to ensure that, you should close the objects in individual try catch
blocks so that one failure will not cause other close's to be skipped.
You can try one more thing, I don't see you are using any LONG/ LONG
RAW/BLOB/CLOB columns from your code here. If the table which you are trying
to retrieve data from has this type of data you will benefit from using some
tuning parameters here and may be able to avoid out of memory exceptions,
take a look at the url,
http://e-docs.bea.com/wls/docs61/oracle/advanced.html#1158561
especially, try using,
weblobic.oci.selectBlobChunkSize and set it to something low. you can set
these properties on the connection pool.
sree
"Murali" <[email protected]> wrote in message
news:[email protected]...
>
>
We are using Weblogic 6.1 and Oracle 8.1.7 for an application we aredeveloping.
Usage of callable statement seems to be resulting an a memory leak. Theprogram runs
in a loop and after processing 200 records, java.lang.outofMemoryException is thrown
>
We are unable to figure out a reason for the same.
The code snippet is as below
try
//dbConn = ImportPODBConnect.getDBConnection(dsJNDIName, dsURL);//connect
to DB <br>
dbConn = DBConnect.getDBConnection(dsJNDIName, dsURL);
//query = POQueries.selectPO(poId); //getthe required
query statement from the POQueries utility class
Print.log(" in getPO() ----> ********* before 1st stmt " +System.currentTimeMillis());
>
cstmt = dbConn.prepareCall("{ ? = call PO_HEADER_PROC(?)}");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.setFloat(2, poId);
// execute and retrieve the result set
cstmt.execute();
getPORs = (ResultSet)cstmt.getObject(1);
Print.log(" in getPO() ----> ********* after 1st stmt " +System.currentTimeMillis());
>
if (!getPORs.next()) //if nothing returnedthen
throw an exception
Print.log("Unable to get the required PO:" + poId);
throw new Exception("Unable to get the required PO:" + poId);
else //set all thevariables
of the PO header objects from the result set
pohSl = new POHeaderSl();
pohSl.setOvUserName(getPORs.getString("OVA_USER_NAME"));
pohSl.setOvCompanyName(getPORs.getString("OVA_COMPANY_NAME"));
pohSl.setAgent(getPORs.getString("AGENT"));
pohSl.setApprovalCode(getPORs.getString("APPROVAL_CODE"));
pohSl.setBrand(getPORs.getString("BRAND"));
pohSl.setBusinessSegment(getPORs.getString("BUSINESS_SEGMENT"));
pohSl.setBusinessSubSegment(getPORs.getString("BUSINESS_SUB_SEGMENT"));
pohSl.setBuyDate(getPORs.getString("BUY_DATE"));
pohSl.setCareContentLabel(getPORs.getString("CARE_CONTENT_LABEL"));
pohSl.setCartonMarkings1(getPORs.getString("CARTON_MARKINGS_1"));
pohSl.setCartonMarkings2(getPORs.getString("CARTON_MARKINGS_2"));
pohSl.setCartonMarkings3(getPORs.getString("CARTON_MARKINGS_3"));
pohSl.setCartonMarkings4(getPORs.getString("CARTON_MARKINGS_4"));
pohSl.setComments(getPORs.getString("COMMENTS"));
pohSl.setCommissionPerUnit(getPORs.getString("COMMISSION_PER_UNIT"));
pohSl.setCompanyId(getPORs.getString("COMPANY_ID"));
pohSl.setCompulsoryString(getPORs.getString("COMPULSORY_STRING"));
pohSl.setConTimestamp(getPORs.getString("CON_TIMESTAMP"));
pohSl.setCurrency(getPORs.getString("CURRENCY"));
pohSl.setCustomerBillToNumber(getPORs.getString("CUSTOMER_BILL_TO_NUMBER"));
pohSl.setCustomerLcBank(getPORs.getString("CUSTOMER_LC_BANK"));;
pohSl.setCustomerLcDate(getPORs.getString("CUSTOMER_LC_DATE"));
pohSl.setCustomerLcExpiryDate(getPORs.getString("CUSTOMER_LC_EXPIRY_DATE"));
pohSl.setCustomerLcNumber(getPORs.getString("CUSTOMER_LC_NUMBER"));
pohSl.setCustomerPoNumber(getPORs.getString("CUSTOMER_PO_NUMBER"));
pohSl.setCustomerSaleDept(getPORs.getString("CUSTOMER_SALE_DEPT"));
pohSl.setCustomerShipToNumber(getPORs.getString("CUSTOMER_SHIP_TO_NUMBER"));
pohSl.setCustomerSo(getPORs.getString("CUSTOMER_SO"));
pohSl.setDateLastModifiedErp(getPORs.getString("DATE_LAST_MODIFIED_ERP"));
pohSl.setDateLastModifiedOv(getPORs.getString("DATE_LAST_MODIFIED_OV"));
pohSl.setDateOfActivation(getPORs.getString("DATE_OF_ACTIVATION"));
Print.log(" ******** inside getPO() ----- > ****** built Header" +System.currentTimeMillis()
if(getPORs != null)
getPORs.close();
getPORs = null;
if(cstmt != null)
Print.log("In the close");
cstmt.close();
cstmt = null;
catch (Exception e)
System.out.println(" in dataAccess.getPO() ----- > " + e.toString());
throw new Exception(e.toString()); //if there are anyexceptions
then throw back the exceptions
finally //finally block to release anyconnections
and statement objects
if(getPORs != null)
getPORs.close();
getPORs = null;
if (pstmt!=null)
pstmt.close();
pstmt = null;
if (cstmt!=null)
cstmt.close();
cstmt = null;
if (dbConn!=null)
dbConn.close();
dbConn = null;
return poSl; //return the PO object
Can anyone help with this?

Similar Messages

  • Memory Leak in 8.1.6.0.1 JDBC/OCI for Solaris

    Hello,
    there is a memory leak in the 8.1.6.0.1 JDBC-OCI driver for solaris.
    The leak causes your jvm to eat up all memory
    if you reuse callable statements
    (calling one statement multiple times with
    different values).
    The thin driver has no such problem. Is
    there any fix available ?

    Ok. The code spans multiple classes and
    most of it comes from a customized version
    of the Enhydra Java Application server.
    I have a class called "StandardDBConnection"
    which caches CallableStatements and is a
    wrapperclass for java.sql.DBConnection. The
    interesting method here is "prepareCall":
    * Get a callable statement given an SQL string. If the statement is
    * cached, return that statement, otherwise prepare and save in the
    * cache.
    * @param sql The SQL statement to be called.
    * @return a new CallableStatement object containing the
    * pre-compiled SQL statement.
    * @exception java.sql.SQLException If a database access error occurs
    * statement.
    public synchronized CallableStatement prepareCall(String sql)
    throws SQLException {
    PreparedStatement preparedStmt;
    logDebug ("Prepare call: " + sql);
    validate();
    preparedStmt = (PreparedStatement)preparedStmtCache.get(sql);
    // Check if the object returned by the cache really is a
    // callable statement. if it is not, someone did call first
    // prepareStatement() and now prepareCall() with the same
    // sql. Silently replace the existing cache entry by a
    // callable statement in this case.
    if (preparedStmt instanceof CallableStatement) {
    preparedStmt.clearParameters();
    else {
    // Need to close the old PreparedStatement in case we have to
    // replace it with a CallableStatement
    if (preparedStmt != null) {
    preparedStmt.close();
    else if (preparedStmtCache.size() >= maxPreparedStmts) {
    String key = (String)preparedStmtCache.keys().nextElement();
    ((PreparedStatement) preparedStmtCache.remove(key)).close();
    preparedStmt = connection.prepareCall(sql);
    preparedStmtCache.put(sql, preparedStmt);
    return (CallableStatement)preparedStmt;
    The statements get closed when I close the
    connection:
    boolean closeStmts = true;
    // Close the prepared statements.
    Enumeration e = preparedStmtCache.keys();
    while (e.hasMoreElements() && closeStmts) {
    String key = (String)e.nextElement();
    try {
    ((PreparedStatement)
    preparedStmtCache.remove(key)).close();
    } catch (SQLException except) {
    // Ignore errors, we maybe handling one.
    closeStmts = false;
    log.write(Logger.NOTICE,
    "DBConnection[" + id + "]: " + url +
    "\nUnable to close statements. Continuing....\n");
    In my classes using database queries I just
    use the prepareCall method of DBConnection
    and do not have to care about anything.
    Works perfectly with the thin driver, but
    as soon as I switch to oci... :-|
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by JDBC Dev Team:
    Soda, Rupper,
    Do you mind posting some code that shows us what your code was doing when you notice this leak?
    Thanks.<HR></BLOCKQUOTE>
    null

  • How to determine memory leaks?

    I tried in XCODE, the RUN/ Start with Performance TOol / and tried out the various options. I was running my app and looking to see if it would report increasing memory use but it seemed to be looking at my total system (i was running under the simulator). In general what is the recommended procedure for determining memory leaks, which tool to use, and what tracing can i use?
    How does one look at the retain count of an object? are there system routines that have knonw leaks?

    You took the right path. Once instruments comes up select the Leaks tool. Turn off automatic leak detection. In your app, start off at some known state, do something, and come back to the known state and check for leaks. For instance start off in a view, do something that brings up another view then come back to the original view and check for leaks. Leaks will show you if you leaked. Since you took a very deterministic path then checked it should be straight forward to go to the code and find / fix the leaks. Leaks shows you where the code where the leak was generated.

  • Pro*c multithreaded application has memory leak

    Hi there,
    I posted this message a week ago in OCI section, nobody answer me.
    I am really curious if my application has a bug or the pro*c has a bug.
    Anyone can compile the sample code and test it easily.
    I made multithreaded application which queries dynamic SQL, it works.
    But the memory leaks when i query the SQL statement.
    The more memory leaks, the more i query the SQL statement, even same SQL
    statement.
    I check it with top, shell command.
    My machine is SUN E450, Solaris 8. Oracle 9.2.0.1
    Compiler : gcc (GCC) 3.2.2
    I changed source code which is from
    $(ORACLE_HOME)/precomp/demo/proc/sample10.pc
    the sample10 doesn't need to be multithreaded. But i think it has to work
    correctly if i changed it to multithreaded application.
    the make file and source code will be placed below.
    I have to figure out the problem.
    Please help
    Thanks in advance,
    the make file is below
    HOME = /user/jkku
    ORA = $(ORACLE_HOME)
    CC = gcc
    PROC = proc
    LC_INCL = -I$(HOME)/work/dbmss/libs/include
    lc_incl = include=$(HOME)/work/dbmss/libs/include
    SYS_INCL =
    sys_incl =
    ORA_INCL = -I. \
    -I$(ORA)/precomp/public \
    -I$(ORA)/rdbms/public \
    -I$(ORA)/rdbms/demo \
    -I$(ORA)/rdbms/pbsql/public \
    -I$(ORA)/network/public \
    -DSLMXMX_ENABLE -DSLTS_ENABLE -D_SVID_GETTOD
    INCLUDES = $(LC_INCL) $(SYS_INCL) $(ORA_INCL)
    includes = $(lc_incl) $(sys_incl)
    LC_LIBS =
    SYS_LIBS = -lpthread -lsocket -lnsl -lrt
    ORA_LIBS = -L$(ORA)/lib/ -lclntsh
    LIBS = $(LC_LIBS) $(SYS_LIBS) $(ORA_LIBS)
    # Define C Compiler flags
    CFLAGS += -D_Solaris64_ -m64
    CFLAGS += -g -D_REENTRANT
    # Define pro*c Compiler flags
    PROCFLAGS += THREADS=YES
    PROCFLAGS += CPOOL=YES
    # Our object files
    PRECOMPS = sample10.c
    OBJS = sample10.o
    .SUFFIXES: .o .c .pc
    .c.o:
    $(CC) -c $(CFLAGS) $(INCLUDES) $*.c
    .pc.c:
    $(PROC) $(PROCFLAGS) $(includes) $*.pc $*.c
    all: sample10
    sample10: $(PRECOMPS) $(OBJS)
    $(CC) $(CFLAGS) -o sample10 $(OBJS) $(LIBS)
    clean:
    rm -rf *.o sample10 sample10.c
    the source code is below which i changed the oracle sample10.pc to
    multithreaded application.
    Sample Program 10: Dynamic SQL Method 4
    This program connects you to ORACLE using your username and
    password, then prompts you for a SQL statement. You can enter
    any legal SQL statement. Use regular SQL syntax, not embedded SQL.
    Your statement will be processed. If it is a query, the rows
    fetched are displayed.
    You can enter multi-line statements. The limit is 1023 characters.
    This sample program only processes up to MAX_ITEMS bind variables and
    MAX_ITEMS select-list items. MAX_ITEMS is #defined to be 40.
    #include <stdio.h>
    #include <string.h>
    #include <setjmp.h>
    #include <sqlda.h>
    #include <stdlib.h>
    #include <sqlcpr.h>
    /* Maximum number of select-list items or bind variables. */
    #define MAX_ITEMS 40
    /* Maximum lengths of the names of the
    select-list items or indicator variables. */
    #define MAX_VNAME_LEN 30
    #define MAX_INAME_LEN 30
    #ifndef NULL
    #define NULL 0
    #endif
    /* Prototypes */
    #if defined(__STDC__)
    void sql_error(void);
    int oracle_connect(void);
    int alloc_descriptors(int, int, int);
    int get_dyn_statement(void);
    void set_bind_variables(void);
    void process_select_list(void);
    void help(void);
    #else
    void sql_error(/*_ void _*/);
    int oracle_connect(/*_ void _*/);
    int alloc_descriptors(/*_ int, int, int _*/);
    int get_dyn_statement(/* void _*/);
    void set_bind_variables(/*_ void -*/);
    void process_select_list(/*_ void _*/);
    void help(/*_ void _*/);
    #endif
    char *dml_commands[] = {"SELECT", "select", "INSERT", "insert",
    "UPDATE", "update", "DELETE", "delete"};
    EXEC SQL INCLUDE sqlda;
    EXEC SQL INCLUDE sqlca;
    EXEC SQL BEGIN DECLARE SECTION;
    char dyn_statement[1024];
    EXEC SQL VAR dyn_statement IS STRING(1024);
    EXEC SQL END DECLARE SECTION;
    EXEC ORACLE OPTION (ORACA=YES);
    EXEC ORACLE OPTION (RELEASE_CURSOR=YES);
    SQLDA *bind_dp;
    SQLDA *select_dp;
    /* Define a buffer to hold longjmp state info. */
    jmp_buf jmp_continue;
    char *db_uid="dbmuser/dbmuser@dbmdb";
    sql_context ctx;
    int err_sql;
    enum{
    SQL_SUCC=0,
    SQL_ERR,
    SQL_NOTFOUND,
    SQL_UNIQUE,
    SQL_DISCONNECT,
    SQL_NOTNULL
    int main()
    int i;
    EXEC SQL ENABLE THREADS;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    /* Connect to the database. */
    if (connect_database() < 0)
    exit(1);
    EXEC SQL CONTEXT USE :ctx;
    /* Process SQL statements. */
    for (;;)
    /* Allocate memory for the select and bind descriptors. */
    if (alloc_descriptors(MAX_ITEMS, MAX_VNAME_LEN, NAME_LEN) != 0)
    exit(1);
    (void) setjmp(jmp_continue);
    /* Get the statement. Break on "exit". */
    if (get_dyn_statement() != 0)
    break;
    EXEC SQL PREPARE S FROM :dyn_statement;
    EXEC SQL DECLARE C CURSOR FOR S;
    /* Set the bind variables for any placeholders in the
    SQL statement. */
    set_bind_variables();
    /* Open the cursor and execute the statement.
    * If the statement is not a query (SELECT), the
    * statement processing is completed after the
    * OPEN.
    EXEC SQL OPEN C USING DESCRIPTOR bind_dp;
    /* Call the function that processes the select-list.
    * If the statement is not a query, this function
    * just returns, doing nothing.
    process_select_list();
    /* Tell user how many rows processed. */
    for (i = 0; i < 8; i++)
    if (strncmp(dyn_statement, dml_commands, 6) == 0)
    printf("\n\n%d row%c processed.\n", sqlca.sqlerrd[2], sqlca.sqlerrd[2] == 1 ? '\0' : 's');
    break;
    /* Close the cursor. */
    EXEC SQL CLOSE C;
    /* When done, free the memory allocated for pointers in the bind and
    select descriptors. */
    for (i = 0; i < MAX_ITEMS; i++)
    if (bind_dp->V != (char *) 0)
    free(bind_dp->V);
    free(bind_dp->I); /* MAX_ITEMS were allocated. */
    if (select_dp->V != (char *) 0)
    free(select_dp->V);
    free(select_dp->I); /* MAX_ITEMS were allocated. */
    /* Free space used by the descriptors themselves. */
    SQLSQLDAFree(ctx, bind_dp);
    SQLSQLDAFree(ctx, select_dp);
    } /* end of for(;;) statement-processing loop */
    disconnect_database();
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    puts("\nHave a good day!\n");
    return;
    * Allocate the BIND and SELECT descriptors using sqlald().
    * Also allocate the pointers to indicator variables
    * in each descriptor. The pointers to the actual bind
    * variables and the select-list items are realloc'ed in
    * the set_bind_variables() or process_select_list()
    * routines. This routine allocates 1 byte for select_dp->V
    * and bind_dp->V, so the realloc will work correctly.
    alloc_descriptors(size, max_vname_len, max_iname_len)
    int size;
    int max_vname_len;
    int max_iname_len;
    int i;
    * The first sqlald parameter determines the maximum number of
    * array elements in each variable in the descriptor. In
    * other words, it determines the maximum number of bind
    * variables or select-list items in the SQL statement.
    * The second parameter determines the maximum length of
    * strings used to hold the names of select-list items
    * or placeholders. The maximum length of column
    * names in ORACLE is 30, but you can allocate more or less
    * as needed.
    * The third parameter determines the maximum length of
    * strings used to hold the names of any indicator
    * variables. To follow ORACLE standards, the maximum
    * length of these should be 30. But, you can allocate
    * more or less as needed.
    if ((bind_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) ==
    (SQLDA *) 0)
    fprintf(stderr,
    "Cannot allocate memory for bind descriptor.");
    return -1; /* Have to exit in this case. */
    if ((select_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) == (SQLDA *)
    0)
    fprintf(stderr,
    "Cannot allocate memory for select descriptor.");
    return -1;
    select_dp->N = MAX_ITEMS;
    /* Allocate the pointers to the indicator variables, and the
    actual data. */
    for (i = 0; i < MAX_ITEMS; i++) {
    bind_dp->I = (short *) malloc(sizeof (short));
    select_dp->I = (short *) malloc(sizeof(short));
    bind_dp->V = (char *) malloc(1);
    select_dp->V = (char *) malloc(1);
    return 0;
    int get_dyn_statement()
    char *cp, linebuf[256];
    int iter, plsql;
    for (plsql = 0, iter = 1; ;)
    if (iter == 1)
    printf("\nSQL> ");
    dyn_statement[0] = '\0';
    fgets(linebuf, sizeof linebuf, stdin);
    cp = strrchr(linebuf, '\n');
    if (cp && cp != linebuf)
    *cp = ' ';
    else if (cp == linebuf)
    continue;
    if ((strncmp(linebuf, "EXIT", 4) == 0) ||
    (strncmp(linebuf, "exit", 4) == 0))
    return -1;
    else if (linebuf[0] == '?' ||
    (strncmp(linebuf, "HELP", 4) == 0) ||
    (strncmp(linebuf, "help", 4) == 0))
    help();
    iter = 1;
    continue;
    if (strstr(linebuf, "BEGIN") ||
    (strstr(linebuf, "begin")))
    plsql = 1;
    strcat(dyn_statement, linebuf);
    if ((plsql && (cp = strrchr(dyn_statement, '/'))) ||
    (!plsql && (cp = strrchr(dyn_statement, ';'))))
    *cp = '\0';
    break;
    else
    iter++;
    printf("%3d ", iter);
    return 0;
    void set_bind_variables()
    int i, n;
    char bind_var[64];
    /* Describe any bind variables (input host variables) */
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    bind_dp->N = MAX_ITEMS; /* Initialize count of array elements. */
    EXEC SQL DESCRIBE BIND VARIABLES FOR S INTO bind_dp;
    /* If F is negative, there were more bind variables
    than originally allocated by sqlald(). */
    if (bind_dp->F < 0)
    printf ("\nToo many bind variables (%d), maximum is %d\n.",
    -bind_dp->F, MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    bind_dp->N = bind_dp->F;
    /* Get the value of each bind variable as a
    * character string.
    * C contains the length of the bind variable
    * name used in the SQL statement.
    * S contains the actual name of the bind variable
    * used in the SQL statement.
    * L will contain the length of the data value
    * entered.
    * V will contain the address of the data value
    * entered.
    * T is always set to 1 because in this sample program
    * data values for all bind variables are entered
    * as character strings.
    * ORACLE converts to the table value from CHAR.
    * I will point to the indicator value, which is
    * set to -1 when the bind variable value is "null".
    for (i = 0; i < bind_dp->F; i++)
    printf ("\nEnter value for bind variable %.*s: ",
    (int)bind_dp->C, bind_dp->S);
    fgets(bind_var, sizeof bind_var, stdin);
    /* Get length and remove the new line character. */
    n = strlen(bind_var) - 1;
    /* Set it in the descriptor. */
    bind_dp->L = n;
    /* (re-)allocate the buffer for the value.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    bind_dp->V = (char *) realloc(bind_dp->V, (bind_dp->L + 1));
    /* And copy it in. */
    strncpy(bind_dp->V, bind_var, n);
    /* Set the indicator variable's value. */
    if ((strncmp(bind_dp->V, "NULL", 4) == 0) ||
    (strncmp(bind_dp->V, "null", 4) == 0))
    *bind_dp->I = -1;
    else
    *bind_dp->I = 0;
    /* Set the bind datatype to 1 for CHAR. */
    bind_dp->T = 1;
    return;
    void process_select_list()
    int i, null_ok, precision, scale;
    if ((strncmp(dyn_statement, "SELECT", 6) != 0) &&
    (strncmp(dyn_statement, "select", 6) != 0))
    select_dp->F = 0;
    return;
    /* If the SQL statement is a SELECT, describe the
    select-list items. The DESCRIBE function returns
    their names, datatypes, lengths (including precision
    and scale), and NULL/NOT NULL statuses. */
    select_dp->N = MAX_ITEMS;
    EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;
    /* If F is negative, there were more select-list
    items than originally allocated by sqlald(). */
    if (select_dp->F < 0)
    printf ("\nToo many select-list items (%d), maximum is %d\n",
    -(select_dp->F), MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    select_dp->N = select_dp->F;
    /* Allocate storage for each select-list item.
    sqlprc() is used to extract precision and scale
    from the length (select_dp->L).
    sqlnul() is used to reset the high-order bit of
    the datatype and to check whether the column
    is NOT NULL.
    CHAR datatypes have length, but zero precision and
    scale. The length is defined at CREATE time.
    NUMBER datatypes have precision and scale only if
    defined at CREATE time. If the column
    definition was just NUMBER, the precision
    and scale are zero, and you must allocate
    the required maximum length.
    DATE datatypes return a length of 7 if the default
    format is used. This should be increased to
    9 to store the actual date character string.
    If you use the TO_CHAR function, the maximum
    length could be 75, but will probably be less
    (you can see the effects of this in SQL*Plus).
    ROWID datatype always returns a fixed length of 18 if
    coerced to CHAR.
    LONG and
    LONG RAW datatypes return a length of 0 (zero),
    so you need to set a maximum. In this example,
    it is 240 characters.
    printf ("\n");
    for (i = 0; i < select_dp->F; i++)
    char title[MAX_VNAME_LEN];
    /* Turn off high-order bit of datatype (in this example,
    it does not matter if the column is NOT NULL). */
    sqlnul ((unsigned short *)&(select_dp->T), (unsigned short
    *)&(select_dp->T), &null_ok);
    switch (select_dp->T)
    case 1 : /* CHAR datatype: no change in length
    needed, except possibly for TO_CHAR
    conversions (not handled here). */
    break;
    case 2 : /* NUMBER datatype: use sqlprc() to
    extract precision and scale. */
    sqlprc ((unsigned int *)&(select_dp->L), &precision,
    &scale);
    /* Allow for maximum size of NUMBER. */
    if (precision == 0) precision = 40;
    /* Also allow for decimal point and
    possible sign. */
    /* convert NUMBER datatype to FLOAT if scale > 0,
    INT otherwise. */
    if (scale > 0)
    select_dp->L = sizeof(float);
    else
    select_dp->L = sizeof(int);
    break;
    case 8 : /* LONG datatype */
    select_dp->L = 240;
    break;
    case 11 : /* ROWID datatype */
    case 104 : /* Universal ROWID datatype */
    select_dp->L = 18;
    break;
    case 12 : /* DATE datatype */
    select_dp->L = 9;
    break;
    case 23 : /* RAW datatype */
    break;
    case 24 : /* LONG RAW datatype */
    select_dp->L = 240;
    break;
    /* Allocate space for the select-list data values.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    if (select_dp->T != 2)
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L + 1);
    else
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L);
    /* Print column headings, right-justifying number
    column headings. */
    /* Copy to temporary buffer in case name is null-terminated */
    memset(title, ' ', MAX_VNAME_LEN);
    strncpy(title, select_dp->S, select_dp->C);
    if (select_dp->T == 2)
    if (scale > 0)
    printf ("%.*s ", select_dp->L+3, title);
    else
    printf ("%.*s ", select_dp->L, title);
    else
    printf("%-.*s ", select_dp->L, title);
    /* Coerce ALL datatypes except for LONG RAW and NUMBER to
    character. */
    if (select_dp->T != 24 && select_dp->T != 2)
    select_dp->T = 1;
    /* Coerce the datatypes of NUMBERs to float or int depending on
    the scale. */
    if (select_dp->T == 2)
    if (scale > 0)
    select_dp->T = 4; /* float */
    else
    select_dp->T = 3; /* int */
    printf ("\n\n");
    /* FETCH each row selected and print the column values. */
    EXEC SQL WHENEVER NOT FOUND GOTO end_select_loop;
    for (;;)
    EXEC SQL FETCH C USING DESCRIPTOR select_dp;
    /* Since each variable returned has been coerced to a
    character string, int, or float very little processing
    is required here. This routine just prints out the
    values on the terminal. */
    for (i = 0; i < select_dp->F; i++)
    if (*select_dp->I < 0)
    if (select_dp->T == 4)
    printf ("%-*c ",(int)select_dp->L+3, ' ');
    else
    printf ("%-*c ",(int)select_dp->L, ' ');
    else
    if (select_dp->T == 3) /* int datatype */
    printf ("%*d ", (int)select_dp->L,
    *(int *)select_dp->V);
    else if (select_dp->T == 4) /* float datatype */
    printf ("%*.2f ", (int)select_dp->L,
    *(float *)select_dp->V);
    else /* character string */
    printf ("%-*.*s ", (int)select_dp->L,
    (int)select_dp->L, select_dp->V);
    printf ("\n");
    end_select_loop:
    return;
    void help()
    puts("\n\nEnter a SQL statement or a PL/SQL block at the SQL> prompt.");
    puts("Statements can be continued over several lines, except");
    puts("within string literals.");
    puts("Terminate a SQL statement with a semicolon.");
    puts("Terminate a PL/SQL block (which can contain embedded
    semicolons)");
    puts("with a slash (/).");
    puts("Typing \"exit\" (no semicolon needed) exits the program.");
    puts("You typed \"?\" or \"help\" to get this message.\n\n");
    int connect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT ALLOCATE :ctx;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL CONNECT :db_uid;
    if(err_sql != SQL_SUCC){
    printf("err => connect database(ctx:%ld, uid:%s) failed!\n", ctx, db_uid);
    return -1;
    return 1;
    int disconnect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL COMMIT WORK RELEASE;
    EXEC SQL CONTEXT FREE:ctx;
    return 1;
    void sql_error()
    printf("err => %.*s", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
    printf("in \"%.*s...\'\n", oraca.orastxt.orastxtl, oraca.orastxt.orastxtc);
    printf("on line %d of %.*s.\n\n", oraca.oraslnr, oraca.orasfnm.orasfnml,
    oraca.orasfnm.orasfnmc);
    switch(sqlca.sqlcode) {
    case -1: /* unique constraint violated */
    err_sql = SQL_UNIQUE;
    break;
    case -1012: /* not logged on */
    case -1089:
    case -3133:
    case -1041:
    case -3114:
    case -3113:
    /* �6�Ŭ�� shutdown�ǰų� �α��� ���°� �ƴҶ� ��b�� �õ� */
    /* immediate shutdown in progress - no operations are permitted */
    /* end-of-file on communication channel */
    /* internal error. hostdef extension doesn't exist */
    err_sql = SQL_DISCONNECT;
    break;
    case -1400:
    err_sql = SQL_NOTNULL;
    break;
    default:
    err_sql = SQL_ERR;
    break;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL ROLLBACK WORK;
    void sql_not_found()
    err_sql = SQL_NOTFOUND;

    Hi Jane,
    What version of Berkeley DB XML are you using?
    What is your operating system and your hardware platform?
    For how long have been the application running?
    What is your current container size?
    What's set for EnvironmentConfig.setThreaded?
    Do you know if containers have previously not been closed correctly?
    Can you please post the entire error output?
    What's the JDK version, 1.4 or 1.5?
    Thanks,
    Bogdan

  • Bug:4705928 PLSQL: Memory leak using small varrays

    We have Oracle version 10.2.0.1.0
    We have a problem with a procedure.
    In our scenario we make use of VARRAY in the procedure to pass some filter parameters to a select distinct querying a view made on three tables.
    Unfotunately not always execution it is successful.
    Sometimes it returns wrong value (0 for the count parameter), sometimes (rarely) the server stops working.
    We suspect that this is caused by a bug fixed in versione 10.2.0.3.0
    Bug:4705928 PLSQL: Memory leak using small varrays when trimming the whole collection and inserting into it in a loop
    We suspect this becasue we made two procedure the first (spProductCount) uses a function (fnProductFilter) to calculate the values of a varray and passes them into the select,
    while in the second procedure (spProductCount2) parameters are passed directly into the statement without varray
    and there are failures only in the first procedure.
    On the other hand on another server 10.2.0.1.0 we never have this problem.
    The instance manifesting the bug runs under shared mode, while the other is under dedicated mode.
    Turning the first one to dedicated mode makes the bugs disapear.
    Unfortunately this is not a solution.
    In the sample there are the three table with all constraints, the view, tha varray custom type, the function and the two procedures.
    Is there someone that may examine our sample and tell us if the pl/sql code corresponds to the bug desciption.
    We also want to know if it's possibile that the same server running under different mode (SHARED/DEDICATED) doesn't behave the same way.
    The tables:
    --Products
    CREATE TABLE "Products" (
         "Image" BLOB
         , "CatalogId" RAW(16)
         , "ProductId" RAW(16)
         , "MnemonicId" NVARCHAR2(50) DEFAULT ''
         , "ProductParentId" RAW(16)
    ALTER TABLE "Products"
         ADD CONSTRAINT "NN_Products_M04" CHECK ("CatalogId" IS NOT NULL)
    ALTER TABLE "Products"
         ADD CONSTRAINT "NN_Products_M05" CHECK ("ProductId" IS NOT NULL)
    ALTER TABLE "Products"
    ADD CONSTRAINT "PK_Products"
    PRIMARY KEY ("ProductId")
    CREATE INDEX "IX_Products"
    ON "Products" ("CatalogId", "MnemonicId")
    CREATE UNIQUE INDEX "UK_Products"
    ON "Products" (DECODE("MnemonicId", NULL, NULL, RAWTOHEX("CatalogId") || "MnemonicId"))
    --Languages
    CREATE TABLE "Languages" (
         "Description" NVARCHAR2(250)
         , "IsStandard" NUMBER(1)
         , "LanguageId" RAW(16)
         , "MnemonicId" NVARCHAR2(12)
    ALTER TABLE "Languages"
         ADD CONSTRAINT "NN_Languages_M01" CHECK ("LanguageId" IS NOT NULL)
    ALTER TABLE "Languages"
         ADD CONSTRAINT "NN_Languages_M05" CHECK ("MnemonicId" IS NOT NULL)
    ALTER TABLE "Languages"
    ADD CONSTRAINT "PK_Languages"
    PRIMARY KEY ("LanguageId")
    ALTER TABLE "Languages"
    ADD CONSTRAINT "UK_Languages"
    UNIQUE ("MnemonicId")
    --ProductDesc
    CREATE TABLE "ProductDesc" (
         "Comment" NCLOB
         , "PlainComment" NCLOB
         , "Description" NVARCHAR2(250)
         , "DescriptionText" NCLOB
         , "PlainDescriptionText" NCLOB
         , "LanguageId" NVARCHAR2(12)
         , "ProductId" RAW(16)
    ALTER TABLE "ProductDesc"
         ADD CONSTRAINT "NN_ProductDescM01" CHECK ("LanguageId" IS NOT NULL)
    ALTER TABLE "ProductDesc"
         ADD CONSTRAINT "NN_ProductDescM02" CHECK ("ProductId" IS NOT NULL)
    ALTER TABLE "ProductDesc"
    ADD CONSTRAINT "PK_ProductDesc"
    PRIMARY KEY ("ProductId", "LanguageId")
    ALTER TABLE "ProductDesc"
    ADD CONSTRAINT "FK_ProductDesc1"
    FOREIGN KEY("ProductId") REFERENCES "Products" ("ProductId")
    ALTER TABLE "ProductDesc"
    ADD CONSTRAINT "FK_ProductDesc2"
    FOREIGN KEY("LanguageId") REFERENCES "Languages" ("MnemonicId")
    /The view:
    --ProductView
    CREATE OR REPLACE VIEW "vwProducts"
    AS
         SELECT
               "Products"."CatalogId"
              , "ProductDesc"."Comment"
              , "ProductDesc"."PlainComment"
              , "ProductDesc"."Description"
              , "ProductDesc"."DescriptionText"
              , "ProductDesc"."PlainDescriptionText"
              , "Products"."Image"
              , "Languages"."MnemonicId" "LanguageId"
              , "Products"."MnemonicId"
              , "Products"."ProductId"
              , "Products"."ProductParentId"
              , TRIM(NVL("ProductDesc"."Description" || ' ', '') || NVL("ParentDescriptions"."Description", '')) "FullDescription"
         FROM "Products"
         CROSS JOIN "Languages"
         LEFT OUTER JOIN "ProductDesc"
         ON "Products"."ProductId" = "ProductDesc"."ProductId"
         AND "ProductDesc"."LanguageId" = "Languages"."MnemonicId"
         LEFT OUTER JOIN "ProductDesc" "ParentDescriptions"
         ON "Products"."ProductParentId" = "ParentDescriptions"."ProductId"
         AND ("ParentDescriptions"."LanguageId" = "Languages"."MnemonicId")
    /The varray:
    --CustomType VARRAY
    CREATE OR REPLACE TYPE Varray_Params IS VARRAY(100) OF NVARCHAR2(1000);
    /The function:
    --FilterFunction
    CREATE OR REPLACE FUNCTION "fnProductFilter" (
         parCatalogId "Products"."CatalogId"%TYPE,
         parLanguageId                    NVARCHAR2 := N'it-IT',
         parFilterValues                    OUT Varray_Params
    RETURN INTEGER
    AS
         varSqlCondition                    VARCHAR2(32000);
         varSqlConditionValues          NVARCHAR2(32000);
         varSql                              NVARCHAR2(32000);
         varDbmsCursor                    INTEGER;
         varDbmsResult                    INTEGER;
         varSeparator                    VARCHAR2(2);
         varFilterValue                    NVARCHAR2(1000);
         varCount                         INTEGER;
    BEGIN
         varSqlCondition := '(T_Product."CatalogId" = HEXTORAW(:parentId)) AND (T_Product."LanguageId" = :languageId )';
         varSqlConditionValues := CHR(39) || TO_CHAR(parCatalogId) || CHR(39) || N', ' || CHR(39 USING NCHAR_CS) || parLanguageId || CHR(39 USING NCHAR_CS);
         parFilterValues := Varray_Params();
         varSql := N'SELECT FilterValues.column_value FilterValue FROM TABLE(Varray_Params(' || varSqlConditionValues || N')) FilterValues';
         BEGIN
              varDbmsCursor := dbms_sql.open_cursor;
              dbms_sql.parse(varDbmsCursor, varSql, dbms_sql.native);
              dbms_sql.define_column(varDbmsCursor, 1, varFilterValue, 1000);
              varDbmsResult := dbms_sql.execute(varDbmsCursor);
              varCount := 0;
              LOOP
                   IF (dbms_sql.fetch_rows(varDbmsCursor) > 0) THEN
                        varCount := varCount + 1;
                        dbms_sql.column_value(varDbmsCursor, 1, varFilterValue);
                        parFilterValues.extend(1);
                        parFilterValues(varCount) := varFilterValue;
                   ELSE
                        -- No more rows to copy
                        EXIT;
                   END IF;
              END LOOP;
              dbms_sql.close_cursor(varDbmsCursor);
         EXCEPTION WHEN OTHERS THEN
              dbms_sql.close_cursor(varDbmsCursor);
              RETURN 0;
         END;
         FOR i in parFilterValues.first .. parFilterValues.last LOOP
              varSeparator := ', ';
         END LOOP;
         RETURN 1;
    END;
    /The procedures:
    --Procedure presenting anomaly\bug
    CREATE OR REPLACE PROCEDURE "spProductCount" (
         parCatalogId "Products"."CatalogId"%TYPE,
         parLanguageId NVARCHAR2 := N'it-IT',
         parRecords OUT NUMBER
    AS
         varFilterValues Varray_Params;
         varResult INTEGER;
         varSqlTotal VARCHAR2(32000);
    BEGIN
         parRecords := 0;
         varResult := "fnProductFilter"(parCatalogId, parLanguageId, varFilterValues);
         varSqlTotal := 'BEGIN
         SELECT count(DISTINCT T_Product."ProductId") INTO :parCount FROM "vwProducts" T_Product
              WHERE ((T_Product."CatalogId" = HEXTORAW(:parentId)) AND (T_Product."LanguageId" = :languageId ));
    END;';
         EXECUTE IMMEDIATE varSqlTotal USING OUT parRecords, varFilterValues(1), varFilterValues(2);
    END;
    --Procedure NOT presenting anomaly\bug
    CREATE OR REPLACE PROCEDURE "spProductCount2" (
         parCatalogId "Products"."CatalogId"%TYPE,
         parLanguageId NVARCHAR2 := N'it-IT',
         parRecords OUT NUMBER
    AS
         varFilterValues Varray_Params;
         varResult INTEGER;
         varSqlTotal VARCHAR2(32000);
    BEGIN
         parRecords := 0;
         varSqlTotal := 'BEGIN
         SELECT count(DISTINCT T_Product."ProductId") INTO :parCount FROM "vwProducts" T_Product
              WHERE ((T_Product."CatalogId" = HEXTORAW(:parentId)) AND (T_Product."LanguageId" = :languageId ));
    END;';
         EXECUTE IMMEDIATE varSqlTotal USING OUT parRecords, parCatalogId, parLanguageId;
    END;Edited by: 835125 on 2011-2-9 1:31

    835125 wrote:
    Using VARRAY was the only way I found to transform comma seprated text values (e.g. "'abc', 'def', '123'") in a collection of strings.A varray is just a functionally crippled version of a nested table collection type, with a defined limit you probably don't need. (Why 100 specifically?) Instead of
    CREATE OR REPLACE TYPE varray_params AS VARRAY(100) OF NVARCHAR2(1000);try
    CREATE OR REPLACE TYPE array_params AS TABLE OF NVARCHAR2(1000);I don't know whether that will solve the problem but at least it'll be a slightly more useful type.
    What makes you think it's a memory leak specifically? Do you observe session PGA memory use going up more than it should?
    btw good luck with all those quoted column names. I wouldn't like to have to work with those, although they do make the forum more colourful.
    Edited by: William Robertson on Feb 11, 2011 7:54 AM

  • Memory leak in weblogic 6.0 sp2 oracle 8.1.7 thin driver

    Hi,
         I have a simple client that opens a database connection, selects from
    a table containing five rows of data (with four columns in each row)
    and then closes all connections. On running this in a loop, I get the
    following error after some time:
    <Nov 28, 2001 5:57:40 PM GMT+06:00> <Error> <Adapter>
    <OutOfMemoryError in
    Adapter
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    <Nov 28, 2001 5:57:40 PM GMT+06:00> <Error> <Kernel> <ExecuteRequest
    failed
    java.lang.OutOfMemoryError
    I am running with a heap size of 64 Mb. The java command that runs
    the client is:
    java -ms64m -mx64m -cp .:/opt/bea/wlserver6.0/lib/weblogic.jar
    -Djava.naming.f
    actory.initial=weblogic.jndi.WLInitialContextFactory
    -Djava.naming.provider.url=
    t3://garlic:7001 -verbose:gc Test
    The following is the client code that opens the db connection and does
    the select:
    import java.util.*;
    import java.sql.*;
    import javax.naming.*;
    import javax.sql.*;
    public class Test {
    private static final String strQuery = "SELECT * from tblPromotion";
    public static void main(String argv[])
    throws Exception
    String ctxFactory     = System.getProperty
    ("java.naming.factory.initial");
    String providerUrl     = System.getProperty
    ("java.naming.provider.url");
    Properties jndiEnv          = System.getProperties ();
    System.out.println ("ctxFactory : " + ctxFactory);
    System.out.println ("ProviderURL : " + providerUrl);
    Context ctx     = new InitialContext (jndiEnv);
    for (int i=0; i <1000000; i++)
    System.out.println("Running query for the "+i+" time");
    Connection con = null;
    Statement stmnt = null;
    ResultSet rs     = null;
    try
    DataSource ds     = (DataSource) ctx.lookup
    (System.getProperty("eaMDataStore", "jdbc/eaMarket"));
    con = ds.getConnection ();
    stmnt = con.createStatement();
    rs = stmnt.executeQuery(strQuery);
    while (rs.next ())
    //System.out.print(".");
    //System.out.println(".");
    ds = null;
    catch (java.sql.SQLException sqle)
    System.out.println("SQL Exception : "+sqle.getMessage());
    finally
    try {
    rs.close ();
    rs = null;
    //System.out.println("closed result set");
    } catch (Exception e) {
    System.out.println("Exception closing result set");
    try {
    stmnt.close ();
    stmnt = null;
    //System.out.println("closed statement");
    } catch (Exception e) {
    System.out.println("Exception closing result set");
    try {
    con.close();
    con = null;
    //System.out.println("closed connection");
    } catch (Exception e) {
    System.out.println("Exception closing connection");
    I am using the Oracle 8.1.7 thin driver. Please let me know if this
    memory leak is a known issue or if its something I am doing.
    thanks,
    rudy

    Repost in JDBC section ... very serious issue but it may be due to Oracle or
    to WL ... does it happen if you test inside WL itself?
    How many iterations does it take to blow? How long? Does changing to a
    different driver (maybe Cloudscape) have the same result?
    Peace,
    Cameron Purdy
    Tangosol Inc.
    << Tangosol Server: How Weblogic applications are customized >>
    << Download now from http://www.tangosol.com/download.jsp >>
    "R.C." <[email protected]> wrote in message
    news:[email protected]...
    Hi,
    I have a simple client that opens a database connection, selects from
    a table containing five rows of data (with four columns in each row)
    and then closes all connections. On running this in a loop, I get the
    following error after some time:
    <Nov 28, 2001 5:57:40 PM GMT+06:00> <Error> <Adapter>
    <OutOfMemoryError in
    Adapter
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    <Nov 28, 2001 5:57:40 PM GMT+06:00> <Error> <Kernel> <ExecuteRequest
    failed
    java.lang.OutOfMemoryError
    I am running with a heap size of 64 Mb. The java command that runs
    the client is:
    java -ms64m -mx64m -cp .:/opt/bea/wlserver6.0/lib/weblogic.jar
    -Djava.naming.f
    actory.initial=weblogic.jndi.WLInitialContextFactory
    -Djava.naming.provider.url=
    t3://garlic:7001 -verbose:gc Test
    The following is the client code that opens the db connection and does
    the select:
    import java.util.*;
    import java.sql.*;
    import javax.naming.*;
    import javax.sql.*;
    public class Test {
    private static final String strQuery = "SELECT * from tblPromotion";
    public static void main(String argv[])
    throws Exception
    String ctxFactory = System.getProperty
    ("java.naming.factory.initial");
    String providerUrl = System.getProperty
    ("java.naming.provider.url");
    Properties jndiEnv = System.getProperties ();
    System.out.println ("ctxFactory : " + ctxFactory);
    System.out.println ("ProviderURL : " + providerUrl);
    Context ctx = new InitialContext (jndiEnv);
    for (int i=0; i <1000000; i++)
    System.out.println("Running query for the "+i+" time");
    Connection con = null;
    Statement stmnt = null;
    ResultSet rs = null;
    try
    DataSource ds = (DataSource) ctx.lookup
    (System.getProperty("eaMDataStore", "jdbc/eaMarket"));
    con = ds.getConnection ();
    stmnt = con.createStatement();
    rs = stmnt.executeQuery(strQuery);
    while (rs.next ())
    //System.out.print(".");
    //System.out.println(".");
    ds = null;
    catch (java.sql.SQLException sqle)
    System.out.println("SQL Exception : "+sqle.getMessage());
    finally
    try {
    rs.close ();
    rs = null;
    //System.out.println("closed result set");
    } catch (Exception e) {
    System.out.println("Exception closing result set");
    try {
    stmnt.close ();
    stmnt = null;
    //System.out.println("closed statement");
    } catch (Exception e) {
    System.out.println("Exception closing result set");
    try {
    con.close();
    con = null;
    //System.out.println("closed connection");
    } catch (Exception e) {
    System.out.println("Exception closing connection");
    I am using the Oracle 8.1.7 thin driver. Please let me know if this
    memory leak is a known issue or if its something I am doing.
    thanks,
    rudy

  • Memory Leak in Java Server

    Howdy Folks- I wrote a server monitor in java, which I was expecting to run for months at a time without restarting. Apparently there is some slow memory leak which results in an OutOfMemoryError after a few weeks. It's in a production system, so I can't readily add debug statements to the code, and the OutOfMemoryError apparently screwed up the logging, so I didn't get a stack trace in my logs, just an "OutOfMemoryError" went to standard out.
    I'm assuming the problem lies in the code, specifically probably some discarded reference that is not being properly garbage collected? I am using a few different ArrayLists to store some historical information, and I call clear() on these frequently. Is there any known issue with ArrayList or HashMap that the "clear()" method doesn't result in garbage collection of the objects that were in it? I am also doing a "remove(int)" sometimes as well. Any chance the objects cleared or removed would not be garbage collected?
    thanks
    Bleu

    Howdy Folks- I wrote a server monitor in java, which I
    was expecting to run for months at a time without
    restarting. Apparently there is some slow memory leak
    which results in an OutOfMemoryError after a few
    weeks. It's in a production system, so I can't
    readily add debug statements to the code, and the
    OutOfMemoryError apparently screwed up the logging, so
    I didn't get a stack trace in my logs, just an
    "OutOfMemoryError" went to standard out.Are you even attempting to catch Errors? Catching Exceptions will not help with this. It should print the stack trace. When it OOMs it doesn't mess up what's already allocated, it just can't allocate more.
    I'm assuming the problem lies in the code,
    specifically probably some discarded reference that is
    not being properly garbage collected? Most likely, there are references that are never being cleared in your code. Without seeing the code or at least having a better description, I don't think anyone here can help you. Can you set up a test senario and use an Optimizer to see what's going on?
    I am using a
    few different ArrayLists to store some historical
    information, and I call clear() on these frequently.
    Is there any known issue with ArrayList or HashMap
    that the "clear()" method doesn't result in garbage
    collection of the objects that were in it? Not that I know of, no. I doubt that is the problem.

  • Memory Leak in NonPaged pool --- Tag = Cont

    Hi All,
            We are facing memory leak issue on some of our some servers in similar fashion. Leak in Nonpaged pool and as per Poolmon - Tag CONT is consuming most memory. As per Pooltag,
    Cont - <unknown>    - Contiguous physical memory allocations for device drivers
    Systems State is shown below:
    Zoom IN to view ScreenShot clearly
    Now i tried to collect details of allocations using WinDBG (!poolfind Cont) tagged with Cont string, but WINDBG gets stuck when it trying to collect data from NonPaged pool, as shown below:
    Zoom IN to view ScreenShot clearly
    Kernel Memory Dump from one of System can be found
    HERE (315 Megs)!
    Any help here ?
    OS ... VirTuaLiZaTioN ... MaxiMuS ... Fair, Good, Better, Best

    Hi,
    I would envolve another engineer to this topic.
    Thanks for your understanding.
    Roger Lu
    TechNet Community Support

  • Memory Leak in terminateConnection() function. How to resolve it ???

    Hi,
    We are facing a memory leak issue in terminateConnection() function. Here is a sample code regarding that. We have run around 1.5 hours simultaneously and it was consuming around 250MB for this simple program. How could I resolve this problem ?
    bool test()
        string userName = "mapserver";
        string password = "a";
        string connectString = "//localhost:1521/orcl";
        string query = "SELECT GEOMETRY AS GEOM FROM AG_WATER";
        Environment *env = Environment::createEnvironment(Environment::OBJECT);
            Connection *conn;
            Statement *stmt;
            ResultSet *rs;
            try{
                conn = env->createConnection(userName, password, "");
            catch (SQLException ex) {
                printf("ORACLE execution error: [Error Code : %d] : %s\n", ex.getErrorCode(), ex.getMessage().c_str());
                return false;
            env->terminateConnection(conn);
            stmt = NULL;
            conn = NULL;
            rs = NULL;
        Environment::terminateEnvironment(env);
        return true;
    int main()
        OracleResultSet pResultSet;
        while (true) {
            test();
        return 0;
    Does any body help me to find out this problem ???

    This is not a web dynpro related question.  Please restrict the questions in this forum to the Web Dynpro ABAP topic.

  • ITunes 6.0.4(3) memory leak

    I know this topic has popped up on the Windows forum, but I'd like to officially document the same problem in iTunes for OSX.
    Using the iStat Nano widget, I've been monitoring my memory usage when running iTunes. When I first start the program, memory usage jumps to 600 MB. The longer iTunes is open, the more and more memory disappears, whether I'm actively using the program or not (i.e. listening to music). Eventually, this causes a hard crash. By hard crash I mean that I must use the on/off button to reboot the machine. I have had this problem since getting my computer (in mid-March), so there has been at least one iTunes update since then that has not fixed this issue. (I have a previous post on this topic called "iTunes freezing" that was made before I realized that it was caused by a memory leak.)
    I am very, very pleased with my MacBook Pro and I realize that this is not a hardware issue. Has anyone else encountered this problem? Are there any plans to fix it in a future update?
    Thanks in advance for any comments, suggestions, or solutions!
    2.16GHz 15.4" MacBook Pro, 2GB RAM   Mac OS X (10.4.6)   4G 40GB Photo iPod, 5G 2GB nano

    I posted a question this evening on what sounds like the same issue: the link is here:
    http://discussions.apple.com/thread.jspa?threadID=548752
    I think your original post makes clear that this issue is about iTunes itself, it's not about any devices or iPods, not is it to do with the Intel or non-Intel processors... I will try looking at the Memory stats too.
    What baffles me is that I had been using iTunes 6 for quite a long time (and only updating it manually, not automatically) before I ever experienced this.
    My hunch (but what do I know?) is that my initial freeze might have happened for some other reason (too many applications working hard at once, as sometimes happens -- though I have had this happen reasonably often on the PowerBook it is extremely rare on the G5) -- and then in the course of that freeze / crash something in iTunes got corrupted (perhaps the database file that allows iTunes to navigate the iTunes library?)
    By the way, what is the technical name for the total freeze thing (i.e. no beachballs, just complete loss of the mouse and keyboard response, clock stops, no shortcuts working, only PowerButton allows you to shut down).
    Has anyone with this issue tried uninstalling iTunes (by Trashing the App) and reinstalling from a newly-downloaded copy? (I might try that ...)
    PowerMac G5 Dual 1.8GHz, PowerBook G4 12" 1.33GHz   Mac OS X (10.4.5)  
    PowerMac G5 Dual 1.8GHz, PowerBook G4 12" 1.33GHz   Mac OS X (10.4.5)  
    PowerMac G5 Dual 1.8GHz, PowerBook G4 12" 1.33GHz   Mac OS X (10.4.5)  
    PowerMac G5 Dual 1.8GHz, PowerBook G4 12" 1.33GHz   Mac OS X (10.4.5)  
    PowerMac G5 Dual 1.8GHz, PowerBook G4 12" 1.33GHz   Mac OS X (10.4.5)  

  • Memory Leak using CertOpenStore on Windows 2008 R2

    I have a program (runs both 32 and 64 bit ) that when using CertOpenStore results in a memory leak on Windows 2008 R2 only (I haven't tried 2012, but this code has run for years on 2000, 2003, 2008 without issues)
    Sample code to reproduce the issue:
    int main( int argc, char** argv )
    HCERTSTORE store;
    int go = 1;
    while( go ){
    store = CertOpenStore(
    CERT_STORE_PROV_SYSTEM_A,
    0,
    0,
    CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_OPEN_EXISTING_FLAG,
    "MY" );
    if( store ){
    //if( !CertCloseStore( store , CERT_CLOSE_STORE_CHECK_FLAG ) ){
    if( !CertCloseStore( store , CERT_CLOSE_STORE_FORCE_FLAG ) ){
    if( GetLastError() == CRYPT_E_PENDING_CLOSE ){
    printf( "!" );
    else{
    go = 0;
    else{
    go = 0;
    Sleep( 10 );
    return 0;
    The callstack for allocations pretty much are all like this  (this is from a 32 bit process on a 2008R2 box)
          HEAP_ENTRY Size Prev Flags    UserPtr UserSize - state
            02e75af0 000f 0000  [00]   02e75b08    0005e - (busy)
            7724dff2 ntdll!RtlAllocateHeap+0x00000274
            745f6017 AcLayers!malloc+0x00000079
            7460dc96 AcLayers!NS_VirtualRegistry::MakePath+0x00000056
            7460e817 AcLayers!NS_VirtualRegistry::CVirtualRegistry::OpenKeyW+0x000000a9
            7460f21a AcLayers!NS_VirtualRegistry::APIHook_RegOpenKeyExW+0x00000036
            743d2641 AcGenral!NS_WRPMitigation::APIHook_RegOpenKeyExW+0x00000024
            7527a246 crypt32!RegOpenHKCUKeyExU+0x00000055
            7527de26 crypt32!OpenSubKeyEx+0x00000108
            7527e4d8 crypt32!OpenSubKey+0x00000015
            7527ed88 crypt32!OpenSystemRegPathKey+0x00000033
            75281a2f crypt32!EnumPhysicalStore+0x00000162
            75281d0e crypt32!I_CertDllOpenSystemStoreProvW+0x0000015c
            752c9fce crypt32!I_CertDllOpenSystemStoreProvA+0x0000006c
            7527e49a crypt32!CertOpenStore+0x0000010e
    Anyone have any ideas of a hotfix available for this?
    thanks

    Might ask them here about this.
    Windows Desktop Dev forums on MSDN
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

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

  • Memory leak in c++ application

    This one line of code is creating a memory leak in my application and I'm not sure what to do after this statement to prevent this from happening.
    Here's the line of code:
    oracle::occi::PObject * pObject = m_statement->getObject( 3 );

    This forum is for general programming questions, and for questions about Studio.
    Questions specifically about OCCI are more likely to get a helpful answer in the OCCI forum:
    C++ Call Interface (OCCI)
    (You can find this and other data-base related forums at forums.oracle.com, then expand the Oracle Database item, then click "more".)

  • Memory Leak in my JDBC application.

    Hi
    I am experiencing a memory leak in a test application using the JDBC-ODBC bridge to access an MS Access DB.
    I close the result set, statement and connection objects after each query. Even then the memory allocated to the process increases by about 20K after each query.
    Is there anything else I should do apart from closing these objects??
    Thanks a lot for your time.
    Fred.

    I am having the same problem using JDBC-ODBC bridge with the MS SQL server DB. Even after closing all of the objects as specified.
    Sorry couldn't be of much help but check the following link
    http://www.allaire.com/Handlers/index.cfm?ID=12409&Method=Full
    But I do not have a work around for this may be I am not looking at the right response.
    Can some one please help.

  • Memory Leak Lenovo X201 and Windows 8

    Hi,
    I'm having a memory leak issue with my X201 and Windows 8. My system starts almost without memory, taking 6.7 of 7.8 GB RAM.
    More people seem to have the same problem:
    http://answers.microsoft.com/en-us/windows/forum/windows_cp-windows_programs/windows-8-rtm-memory-le...
    I have installed the available beta drivers  but they don't help. Any advice?
    Spec:
    - Windows 8 Enterprise
     - Intel Core i7-620M Processor (2.66GHz, 4MB L3, 1066MHz FSB)
     - Genuine Windows 7 Professional 64
     - Genuine Windows 7 Professional 64 US English
     - 12.1" WXGA LED Panel, 2x2 UltraConnect II antenna; with Camera and Wireless Broadband Upgradeable
     - 8 GB PC3-8500 DDR3 SDRAM 1067MHz SODIMM Memory (2 DIMM)
     - Keyboard UK English
     - TrackPoint with Fingerprint Reader
     - 128 GB Solid State Drive, Serial ATA
     - 5-1 Media Card Reader and Modem
     - ThinkPad X200 Series 9 cell Li-Ion Battery (up to 5 hours life)
      - Country Pack United Kingdom with Line cord & 65W AC adapter
     - Bluetooth w/ antenna
     - Intel Centrino Advanced-N 6200 (2x2 AGN)
     - Integrated Wireless Wide Area Network upgradable

    Does Windows 8 manage memory differently?

Maybe you are looking for

  • How can I transfer everything  from an apple ID to the next

    First I had my frist apple ID, but then It said when I bought something that I needed to answer security questions, and it says my answers are wrong. Is it possible to transfer the apple ID, music anvd videos and all that to the next??? Sincerly Lell

  • Attaching a file to an E-Mail you are replying to?...

    Why has Apple still not added the feature to let you attach a file to an E-Mail you are replying to? Do you know how frustrating it is to have to go to the pic folder and send it thru there, copying and pasting peoples E-Mail address's who are not in

  • [svn:osmf:] 17940: Fix FM-982: MAST plugin doesn' t show preroll for F4M resources.

    Revision: 17940 Revision: 17940 Author:   [email protected] Date:     2010-09-29 14:47:13 -0700 (Wed, 29 Sep 2010) Log Message: Fix FM-982: MAST plugin doesn't show preroll for F4M resources. Ticket Links:     http://bugs.adobe.com/jira/browse/FM-982

  • How streams replicate to a different table?

    How can I replicate a shared object from source database to another table that has the different name of the source table ? anyone who has this experience please give me a example, thanks .

  • Fan view not working in stacks

    I don't have the option at all !! Don't see how I can enable that cool looking fan view. I'm running 10.5.1 and my clicking an icon in my stack just shows the grid view with directory listings. The "options" menu (hold down mouse and then click on a