Skip to content

MemoryLeak: The Spring RDF4JTemplate does not close connections #5325

@jwesselink

Description

@jwesselink

Current Behavior

I'm encountering a memory leak issue caused by RDF4JTemplate not properly closing connections.

The RDF4JTemplate implementation retrieves a connection from the repositoryConnectionFactory but fails to close it. Since a new connection is created for each request, memory usage increases rapidly, leading to a significant memory leak.

According to the Javadoc for Repository, it’s explicitly stated that connections must be closed after use.

I attempted to resolve the issue by overriding consumeConnection and applyToConnection, wrapping the logic in a try-with-resources block. However, this led to problems in my unit tests using MemoryStore, where I started encountering “Connection is already closed” exceptions.

What I don’t understand is why nobody else seems to have run into this issue. For instance, connection pooling also doesn’t work as expected—because connections are never closed, they’re not returned to the pool, eventually exhausting it.

Expected Behavior

The RDF4JTemplate should close the connection and not cause memory leaks.

Steps To Reproduce

Execute the RDF4JTemplate.update query inside a loop, repeating the call 500 times. You'll observe a steady increase in memory usage, or—depending on your JVM memory settings—encounter a java.lang.OutOfMemoryError: Java heap space exception.

Version

5.1.3

Are you interested in contributing a solution yourself?

None

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions