Is there a good way to implement an asynchronous version of synchronized keyword? Obviously the synchronized() keyword will frequently block the current thread. For example:
public static boolean getLockSync(Runnable r) {
if (isLocked) {
r.run();
return true;
}
synchronized (My.lock) { // this is blocking, could block for more than 1-2 ms
isLocked = true;
r.run();
isLocked = false;
return false;
}
}
I can return a boolean from this block - it's synchronous. Is there a way to do this asynchronously?
Something like this:
public static void getLockAsync(Runnable r) {
if (isLocked) {
CompletableFuture.runAsync(r);
return;
}
Object.onLockAcquisition(My.lock, () -> { // this is non-blocking
isLocked = true;
r.run();
isLocked = false;
Object.releaseLock(My.lock);
});
}
I made up the Object.onLockAcquisition method, but looking for something like that.