Browse Source

DATAMONGO-583 - Using while (…) instead of for (…) for DBCursors to avoid memory leak.

Instead of iterating over the DBCursor using a for-loop we now use a while-loop to avoid the potential memory leak outlined in [0].

[0] https://jira.mongodb.org/browse/JAVA-664
1.1.x
Philipp Schneider 13 years ago committed by Oliver Gierke
parent
commit
138a4942e9
  1. 33
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

33
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

@ -1513,7 +1513,12 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
CursorPreparer preparer, DbObjectCallback<T> objectCallback, String collectionName) { CursorPreparer preparer, DbObjectCallback<T> objectCallback, String collectionName) {
try { try {
DBCursor cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
DBCursor cursor = null;
try {
cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
if (preparer != null) { if (preparer != null) {
cursor = preparer.prepare(cursor); cursor = preparer.prepare(cursor);
@ -1521,11 +1526,19 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
List<T> result = new ArrayList<T>(); List<T> result = new ArrayList<T>();
for (DBObject object : cursor) { while (cursor.hasNext()) {
DBObject object = cursor.next();
result.add(objectCallback.doWith(object)); result.add(objectCallback.doWith(object));
} }
return result; return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
} catch (RuntimeException e) { } catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e); throw potentiallyConvertRuntimeException(e);
} }
@ -1535,15 +1548,27 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
DocumentCallbackHandler callbackHandler, String collectionName) { DocumentCallbackHandler callbackHandler, String collectionName) {
try { try {
DBCursor cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
DBCursor cursor = null;
try {
cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
if (preparer != null) { if (preparer != null) {
cursor = preparer.prepare(cursor); cursor = preparer.prepare(cursor);
} }
for (DBObject dbobject : cursor) { while (cursor.hasNext()) {
DBObject dbobject = cursor.next();
callbackHandler.processDocument(dbobject); callbackHandler.processDocument(dbobject);
} }
} finally {
if (cursor != null) {
cursor.close();
}
}
} catch (RuntimeException e) { } catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e); throw potentiallyConvertRuntimeException(e);
} }

Loading…
Cancel
Save