Hazelcast IMap tryLock bulk multiple keys

266 views Asked by At

I have a clustered program where each thread wants to lock a set of keys. As I understood the simplest solution using hazelcast:

private void lock(SortedSet<String> objects) {
    try {
        IMap<String, String> lockMap = getLockMap();
        for (; ; ) {
            SortedSet<String> lockedObjects = new TreeSet<>();
            for (String object : objects) {
                try {
                    boolean locked = lockMap.tryLock(object, 0, null, maxBlockTime, TimeUnit.MILLISECONDS);
                    if (locked) {
                        lockedObjects.add(object);
                    } else {
                            for (String lockedObject : lockedObjects) {
                                lockMap.unlock(lockedObject);
                            }
                            lockedObjects.clear();
                            break;
                    }
                } catch (Exception e) {
                    for (String lockedObject : lockedObjects) {
                       try {
                          lockMap.unlock(lockedObject);
                       } catch(Exception ignored) {
                       }
                    }
                    throw e;
                }
            }

            if (!lockedObjects.isEmpty()) {
                    return lockedObjects;
            }

            Thread.sleep(waitTime);
        }
    }
}

The main problem of this code that this code generates a lot of network traffics and requests to hazelcast. Could somebody recommend how this code can be optimized?

I couldn't find bulk tryLock functionality in the Hazelcast IMap.

1

There are 1 answers

0
tom.bujok On

Hazelcast does not offer a bulkLock method.

You can optimize this code in various ways, but before we get to that it would be great to know why you want to lock these entries and what you are trying to achieve.