Java.Sql.Sqlexception: - Ora-01000: Maximum Open Cursors Exceeded

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

ORA-01000, the maximum-open-cursors error, is an extremely common error in Oracle database development. In the context of Java, it happens when the application attempts to open more ResultSets than there are configured cursors on a database instance.

Common causes are:

  1. Configuration mistake

    • You have more threads in your application querying the database than cursors on the DB. One case is where you have a connection and thread pool larger than the number of cursors on the database.
    • You have many developers or applications connected to the same DB instance (which will probably include many schemas) and together you are using too many connections.
    • Solution:

      • Increasing the number of cursors on the database (if resources allow) or
      • Decreasing the number of threads in the application.
  2. Cursor leak

    • The applications is not closing ResultSets (in JDBC) or cursors (in stored procedures on the database)
    • Solution: Cursor leaks are bugs; increasing the number of cursors on the DB simply delays the inevitable failure. Leaks can be found using static code analysis, JDBC or application-level logging, and database monitoring.

Background

This section describes some of the theory behind cursors and how JDBC should be used. If you don't need to know the background, you can skip this and go straight to 'Eliminating Leaks'.

What is a cursor?

A cursor is a resource on the database that holds the state of a query, specifically the position where a reader is in a ResultSet. Each SELECT statement has a cursor, and PL/SQL stored procedures can open and use as many cursors as they require. You can find out more about cursors on Orafaq.

A database instance typically serves several different schemas, many different users each with multiple sessions. To do this, it has a fixed number of cursors available for all schemas, users and sessions. When all cursors are open (in use) and request comes in that requires a new cursor, the request fails with an ORA-010000 error.

Finding and setting the number of cursors

The number is normally configured by the DBA on installation. The number of cursors currently in use, the maximum number and the configuration can be accessed in the Administrator functions in Oracle SQL Developer. From SQL it can be set with:

ALTER SYSTEM SET OPEN_CURSORS=1337 SID='*' SCOPE=BOTH;

Relating JDBC in the JVM to cursors on the DB

The JDBC objects below are tightly coupled to the following database concepts:

  • JDBC Connection is the client representation of a database session and provides database transactions. A connection can have only a single transaction open at any one time (but transactions can be nested)
  • A JDBC ResultSet is supported by a single cursor on the database. When close() is called on the ResultSet, the cursor is released.
  • A JDBC CallableStatement invokes a stored procedure on the database, often written in PL/SQL. The stored procedure can create zero or more cursors, and can return a cursor as a JDBC ResultSet.

JDBC is thread safe: It is quite OK to pass the various JDBC objects between threads.

For example, you can create the connection in one thread; another thread can use this connection to create a PreparedStatement and a third thread can process the result set. The single major restriction is that you cannot have more than one ResultSet open on a single PreparedStatement at any time. See Does Oracle DB support multiple (parallel) operations per connection?

Note that a database commit occurs on a Connection, and so all DML (INSERT, UPDATE and DELETE's) on that connection will commit together. Therefore, if you want to support multiple transactions at the same time, you must have at least one Connection for each concurrent Transaction.

Closing JDBC objects

A typical example of executing a ResultSet is:

Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery( "SELECT FULL_NAME FROM EMP" );
try {
while ( rs.next() ) {
System.out.println( "Name: " + rs.getString("FULL_NAME") );
}
} finally {
try { rs.close(); } catch (Exception ignore) { }
}
} finally {
try { stmt.close(); } catch (Exception ignore) { }
}

Note how the finally clause ignores any exception raised by the close():

  • If you simply close the ResultSet without the try {} catch {}, it might fail and prevent the Statement being closed
  • We want to allow any exception raised in the body of the try to propagate to the caller.
    If you have a loop over, for example, creating and executing Statements, remember to close each Statement within the loop.

In Java 7, Oracle has introduced the AutoCloseable interface which replaces most of the Java 6 boilerplate with some nice syntactic sugar.

Holding JDBC objects

JDBC objects can be safely held in local variables, object instance and class members. It is generally better practice to:

  • Use object instance or class members to hold JDBC objects that are reused multiple times over a longer period, such as Connections and PreparedStatements
  • Use local variables for ResultSets since these are obtained, looped over and then closed typically within the scope of a single function.

There is, however, one exception: If you are using EJBs, or a Servlet/JSP container, you have to follow a strict threading model:

  • Only the Application Server creates threads (with which it handles incoming requests)
  • Only the Application Server creates connections (which you obtain from the connection pool)
  • When saving values (state) between calls, you have to be very careful. Never store values in your own caches or static members - this is not safe across clusters and other weird conditions, and the Application Server may do terrible things to your data. Instead use stateful beans or a database.
  • In particular, never hold JDBC objects (Connections, ResultSets, PreparedStatements, etc) over different remote invocations - let the Application Server manage this. The Application Server not only provides a connection pool, it also caches your PreparedStatements.

Eliminating leaks

There are a number of processes and tools available for helping detect and eliminating JDBC leaks:

  1. During development - catching bugs early is by far the best approach:

    1. Development practices: Good development practices should reduce the number of bugs in your software before it leaves the developer's desk. Specific practices include:

      1. Pair programming, to educate those without sufficient experience
      2. Code reviews because many eyes are better than one
      3. Unit testing which means you can exercise any and all of your code base from a test tool which makes reproducing leaks trivial
      4. Use existing libraries for connection pooling rather than building your own
    2. Static Code Analysis: Use a tool like the excellent Findbugs to perform a static code analysis. This picks up many places where the close() has not been correctly handled. Findbugs has a plugin for Eclipse, but it also runs standalone for one-offs, has integrations into Jenkins CI and other build tools

  2. At runtime:

    1. Holdability and commit

      1. If the ResultSet holdability is ResultSet.CLOSE_CURSORS_OVER_COMMIT, then the ResultSet is closed when the Connection.commit() method is called. This can be set using Connection.setHoldability() or by using the overloaded Connection.createStatement() method.
    2. Logging at runtime.

      1. Put good log statements in your code. These should be clear and understandable so the customer, support staff and teammates can understand without training. They should be terse and include printing the state/internal values of key variables and attributes so that you can trace processing logic. Good logging is fundamental to debugging applications, especially those that have been deployed.
      2. You can add a debugging JDBC driver to your project (for debugging - don't actually deploy it). One example (I have not used it) is log4jdbc. You then need to do some simple analysis on this file to see which executes don't have a corresponding close. Counting the open and closes should highlight if there is a potential problem


        1. Monitoring the database. Monitor your running application using the tools such as the SQL Developer 'Monitor SQL' function or Quest's TOAD. Monitoring is described in this article. During monitoring, you query the open cursors (eg from table v$sesstat) and review their SQL. If the number of cursors is increasing, and (most importantly) becoming dominated by one identical SQL statement, you know you have a leak with that SQL. Search your code and review.

Other thoughts

Can you use WeakReferences to handle closing connections?

Weak and soft references are ways of allowing you to reference an object in a way that allows the JVM to garbage collect the referent at any time it deems fit (assuming there are no strong reference chains to that object).

If you pass a ReferenceQueue in the constructor to the soft or weak Reference, the object is placed in the ReferenceQueue when the object is GC'ed when it occurs (if it occurs at all). With this approach, you can interact with the object's finalization and you could close or finalize the object at that moment.

Phantom references are a bit weirder; their purpose is only to control finalization, but you can never get a reference to the original object, so it's going to be hard to call the close() method on it.

However, it is rarely a good idea to attempt to control when the GC is run (Weak, Soft and PhantomReferences let you know after the fact that the object is enqueued for GC). In fact, if the amount of memory in the JVM is large (eg -Xmx2000m) you might never GC the object, and you will still experience the ORA-01000. If the JVM memory is small relative to your program's requirements, you may find that the ResultSet and PreparedStatement objects are GCed immediately after creation (before you can read from them), which will likely fail your program.

TL;DR: The weak reference mechanism is not a good way to manage and close Statement and ResultSet objects.

Getting java.sql.SQLException: - ORA-01000: maximum open cursors exceeded for DML (Update Statement)

Move your preparedStatement.close() inside of while:

preparedStatement = conn.prepareStatement("update table1 set column1='value' where input=?");
while (i.hasNext()) {
XSSFRow row = (XSSFRow) i.next();
input = row.getCell(0).toString();

preparedStatement.clearParameters();
preparedStatement.setString(1, input);
result = preparedStatement.executeUpdate();
}

if (preparedStatement != null) {
preparedStatement.close();
}

When assings a new preparedStatement you are losing the reference and only it is closing the last preparedStatement.

If you use ResultSet on other part of your code, remember close it too if you are doing a loop.

EDIT: Reusing the prepared statement, you can close it outside of loop. More details here

ORA-01000: maximum open cursors exceeded - java code fails

This link will will explain you what a cursor is and how it works.

Yes you can change the maximum number of cursors on Oracle using the following statement:
ALTER SYSTEM SET OPEN_CURSORS=1337 SID='*' SCOPE=BOTH;

But you should do that just if really needed. What you really should do is handle resultset and statements correctly, and ensure that you always close them. This should typically be done in a try/finally statement.

If you forget to close these, open cursors will leak until you reach the maximum limit (which comes very quickly), and subsequent requests won't work (this is the case for you).

You could edit your question and add some code so that we can show you some hint about how and where your may close the resultset and statement properly.

This is typical usage:

Statement stmt;
try {
stmt = con.createStatement();
// do something with the statement
} catch (SQLException e) {
LOG.error("SQL error", e);
} finally {
try { if (stmt != null) stmt.close(); } catch (SQLException se) { LOG.error("Error closing the statement", se); }
// if using Apache utils you could do
// IOUtils.closeQuietly(stmt);
}

It is the same with resultset. Depending on the version of Java you're using you could use the try-with-resources idiom.

try (Statement stmt = con.createStatement()) {
// do something with the statement
} catch(SQLException e) {
LOG.error("SQL error", e);
}

Java will take care of closing the statement at the end of the try block, since Statement implements the AutoCloseable interface.

Error ORA-01000: maximum open cursors exceeded

You are (or were) setting rs and ps to null in the else, i.e. when rc.getInt(1) == 0. That meens that when you get to the finally block, these tests would fail, and ps and rs could not be closed:

            if (rs != null)
try {
rs.close();
} catch (Exception exx) {
}
....
if (ps != null)
try {
ps.close();
} catch (Exception exx) {
}

As @APC already pointed out, you are also (or were) closing the wrong statement here:

            if (ps2 != null)
try {
ps.close();
} catch (Exception exx) {
}

The bigger problem is that you don't free your connection(s) as you claimed. There is a call to cnnOracle.fermerConnexion(), but only in an exception handler:

...
} catch (Exception ex) {
requete.fermer();

fichierIndius.fermerSansException();
fichierIndius2.fermerSansException();
cnnAS400.fermerConnexion();
cnnAS400FO.fermerConnexion();
cnnOracle.fermerConnexion();
System.err
.println("Erreur d'écriture dans le fichier d'indus! / EXC : "
+ ex);
return;
}
finally{
...

You need to close the connection in the finally block as well, after you (correctly) close the statements and result sets.

You also need to look at what cnnOracle.fermerConnexion() is doing. You call cnnOracle.getConnexion() twice, once for each of your prepared statements. If those return different connections, and fermerConnexion() only closes one, you're leaking there too. You'll need to investigate what happen inside each of them.

It would be more normal to use one connection, so you have a variable called say conn that you set with cnnOracle.getConnexion(), and then create your prepared statments as ps = conn.prepareStatement(...).

You currently seem to be getting connections and recreating and destroying the prepared statements inside a loop. It would be much more efficient to get the connection and prepare the statements once before the loop, and just execute them inside the loop. And then close the prepared statements and connection after the loop completes (and still in the exception handler, since that returns to the caller, and the finally block for the try block will no longer close them).



Related Topics



Leave a reply



Submit