Cmyker
Cmyker

Reputation: 2548

Memory leak with Spring MongoDB stream?

The code below causes presumably memory leak:

public int reregister(ReregisterDTO reregisterDTO) {
    AtomicInteger count = new AtomicInteger(0);

    StreamUtils.createStreamFromIterator(
        mongoTemplate
            .stream(createQuery(reregisterDTO), Shipment.class))
            .forEach(shipment -> this.reregisterShipment(shipment, count)
    );

    return count.get();
}

It has fetched 20000 entities from DB but appears that memory is not released. With even bigger volume JVM ran out of memory completely. How do I free up memory and avoid it? could it be that underlying srping-mongodb code holds reference somewhere?

Memory footprint

UPDATE & FIX:

So apparently I mixed up parentheses here, has to be in this order:

    StreamUtils.createStreamFromIterator(
        mongoTemplate.stream(
            createQuery(reregisterDTO),
            Shipment.class
        )
    ).forEach(shipment -> this.reregisterShipment(shipment, count));

Credits to Qingfei Yuan's answer below.

Upvotes: 2

Views: 1793

Answers (1)

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

Seems you need create stream by StreamUtils.createStreamFromIterator(Iterator<T>) instead of use stream directly.

Please refer to Java 8 stream support in MongoTemplate

Upvotes: 3

Related Questions