Created
July 27, 2021 08:47
-
-
Save basilevs/7e8a4810eb48a06295cb3320f6674224 to your computer and use it in GitHub Desktop.
Locking implementation
This file contains 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
import java.util.Objects; | |
/** Executes a runnable as a critical section but without any blocking. | |
* Number of executions is not guaranteed to match a number of invocations. | |
* Last invocation happens-before last execution. | |
* | |
* **/ | |
public final class ExclusiveRunner implements Runnable { | |
private final Runnable delegate; | |
private final Object lock = new Object(); | |
private boolean requested = false; | |
private boolean busy = false; | |
public ExclusiveRunner(Runnable delegate) { | |
super(); | |
this.delegate = Objects.requireNonNull(delegate); | |
} | |
@Override | |
public void run() { | |
synchronized (lock) { | |
requested = true; | |
if (busy) { | |
return; | |
} | |
busy = true; | |
} | |
for (;;) { | |
synchronized (lock) { | |
if (!requested) { | |
busy = false; | |
return; | |
} | |
requested = false; | |
} | |
delegate.run(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment