Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Useful StripedLock from GridGain

DZone's Guide to

A Useful StripedLock from GridGain

· Big Data Zone ·
Free Resource

The open source HPCC Systems platform is a proven, easy to use solution for managing data at scale. Visit our Easy Guide to learn more about this completely free platform, test drive some code in the online Playground, and get started today.

A pretty cool locking mechanism which we use every now and then at  GridGain is concurrent segmented "striped" locks. Sometimes, your objects are constantly recreated, so you can't really attach a mutex to them. For cases like those you can partition the object space into multiple segments (often by object hashcode value) and only acquire the lock on the segment an object belongs to. This way the more segments you have, the more concurrency you have.

Here is a code for our StripedLock that I thought would be good to share:
 
public class StripedLock {
    // Array of underlying locks.
    private final Lock[] locks;
 
    public StripedLock(int concurrencyLevel) {
        locks = new Lock[concurrencyLevel];
 
        for (int i = 0; i < concurrencyLevel; i++)
            locks[i] = new ReentrantLock();
    }
 
    public int concurrencyLevel() {
        return locks.length;
    }
 
    public Lock getLock(int key) {
        return locks[abs(key) % locks.length];
    }
 
    public Lock getLock(long key) {
        return locks[abs((int)(key % locks.length))];
    }
 
    // Account for Math.abs() returning negative value.
    private int abs(int key) {
        return key == Integer.MIN_VALUE ? 0 : Math.abs(key);
    }
 
    public Lock getLock(@Nullable Object o) {
        return o == null ? locks[0] : getLock(o.hashCode());
    }
 
    public void lock(int key) {
        getLock(key).lock();
    }
 
    public void lock(long key) {
        getLock(key).lock();
    }
 
    public void unlock(int key) {
        getLock(key).unlock();
    }
 
    public void unlock(long key) {
        getLock(key).unlock();
    }
 
    public void lock(@Nullable Object o) {
        getLock(o).lock();
    }
 
    public void unlock(@Nullable Object o) {
        getLock(o).unlock();
    }
}
 

Managing data at scale doesn’t have to be hard. Find out how the completely free, open source HPCC Systems platform makes it easier to update, easier to program, easier to integrate data, and easier to manage clusters. Download and get started today.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}