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
This commit is contained in:
Philipp Schneider
2012-12-06 22:14:47 +01:00
committed by Oliver Gierke
parent cffc27d83a
commit 4c8bf0dec2

View File

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