Last active
June 23, 2020 14:27
-
-
Save ashkrit/f900f06b6cce2fd9b3ef1753578210ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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