Skip to content

Instantly share code, notes, and snippets.

@basilevs
Created July 27, 2021 08:47
Show Gist options
  • Save basilevs/7e8a4810eb48a06295cb3320f6674224 to your computer and use it in GitHub Desktop.
Save basilevs/7e8a4810eb48a06295cb3320f6674224 to your computer and use it in GitHub Desktop.
Locking implementation
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