How should Hazelcast dynamically allocated FencedLocks be destroyed

46 views Asked by At

Hazelcast FencedLocks should be destroyed to avoid memory leaks but how/when should that be done when those locks are not known beforehand and created/allocated on demand (potentially by multiple processes)? Or are those locks not meant to be used that way?

example:

// this method can be called by multiple concurrent processes
public void updateClient(ClientId id, ClientData data) {
    var lock = this.hz.getCPSubsystem().getLock(id.toString());
    lock.lock();
    try {
        // update the client
    } finally {
        lock.unlock();
    }
    // where should lock.destroy() be called?
}
1

There are 1 answers

1
Techies On

According to documentation, a fenced lock is equivalent to a standard lock.

There is no "destroyer" in java.

If no one holds any reference on the created lock, garbage collector will destroy this lock.

According to POO, Hazelcast has the responsability to manage its own locks.

Beware not to retain a reference yourself by creating a field in your class and affecting the reference of the lock for example.

EDIT: Documentation says:

Locks are not automatically removed. If a lock is not used anymore, Hazelcast does not automatically perform garbage collection in the lock. This can lead to an OutOfMemoryError. If you create locks on the fly, make sure they are destroyed.

This is weird.

EDIT2: This is not clear why Hazelcast does not destroy its own locks after using it. Maybe to achieve high performance by not recreating the lock again and again.

There is not a clear consensus on what to do. I advise to destroy the lock after using it to avoid memory leak. If it is a problem (high number of clients/threads accessing the same lock), it seems an IMap should be used.