Bug #1783 ConcurrentModificationException thrown on closing the connection
Submitted: 8 Nov 2003 15:03 Modified: 9 Nov 2003 16:19
Reporter: Andrus Adamchik Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / J Severity:S2 (Serious)
Version:3.1.0-alpha OS:Java
Assigned to: CPU Architecture:Any

[8 Nov 2003 15:03] Andrus Adamchik
Description:
When closing connections that have open Statement objects, there is an exception thrown consistently:

java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextEntry(HashMap.java:762)
	at java.util.HashMap$KeyIterator.next(HashMap.java:798)
	at com.mysql.jdbc.Connection.closeAllOpenStatements(Connection.java:2538)
	at com.mysql.jdbc.Connection.close(Connection.java:1067)

It is quiet obvious from the code why this happens - any statements that are closed in the iterator are trying to modify the map we are iterating over...The patch is attached below.

How to repeat:
Open a connection
Create a Statement
Close the connection

Suggested fix:
--- ../tmp/mysql-connector-java-3.1.0-alpha/mysql-connector-java-3.1.0-alpha/com/mysql/jdbc/Connection.java	Mon Feb 17 12:28:45 2003
+++ mysql-connector-java-3.1.0-alpha/com/mysql/jdbc/Connection.java	Sat Nov  8 17:46:56 2003
@@ -2532,8 +2532,12 @@
      */
     private void closeAllOpenStatements() throws SQLException {
         SQLException postponedException = null;
+        
+        // must iterate over the copy of the statements map,
+        // since each statement will try to remove itself from the map
+        // resulting in ConcurrentModificationException
 
-        for (Iterator iter = this.openStatements.keySet().iterator();
+        for (Iterator iter = new ArrayList(this.openStatements.keySet()).iterator();
                 iter.hasNext();) {
             Statement stmt = (Statement) iter.next();
[9 Nov 2003 16:19] Mark Matthews
This has been fixed in the development tree for quite some time. Please see a nightly snapshot from http://downloads.mysql.com/snapshots.php