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. 55
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

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

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

Loading…
Cancel
Save