Skip to content

Instantly share code, notes, and snippets.

@ashkrit
Last active June 23, 2020 14:27
Show Gist options
  • Select an option

  • Save ashkrit/f900f06b6cce2fd9b3ef1753578210ca to your computer and use it in GitHub Desktop.

Select an option

Save ashkrit/f900f06b6cce2fd9b3ef1753578210ca to your computer and use it in GitHub Desktop.
/*
This is using single Int to manage 32 locks in thread safe way.
This has less memory usage as compared to JDK lock which uses one Int(32 Bytes) to manage single lock.
*/
public class Locks {
public static final int INT_BYTES = 32;
private AtomicInteger lock = new AtomicInteger(0);
public boolean lock(int index) {
int value = lock.get();
if (Bits.isSet(value, index)) {
return false;
}
int newLock = Bits.set(value, index);
return lock.compareAndSet(value, newLock);
}
public boolean release(int index) {
int value = lock.get();
int newLock = Bits.clear(value, index);
return lock.compareAndSet(value, newLock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment