Skip to content

Commit

Permalink
Merge pull request #390 from AxonIQ/enhancement/reentrant-lock-io-yield
Browse files Browse the repository at this point in the history
Use `ReentrantLock` instead of `Thread#yield` to optimize the `SynchronizedRequestStream`
  • Loading branch information
smcvb authored Oct 25, 2024
2 parents 8f915e2 + 26410f4 commit 7fe8aeb
Showing 1 changed file with 4 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.grpc.stub.ClientCallStreamObserver;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;

/**
* Lock-based synchronized implementation of a {@link ClientCallStreamObserver}. Acts as a wrapper of another {@code
Expand All @@ -30,7 +31,7 @@
public class SynchronizedRequestStream<T> extends ClientCallStreamObserver<T> {

private final ClientCallStreamObserver<T> delegate;
private final AtomicBoolean lock = new AtomicBoolean(false);
private final ReentrantLock lock = new ReentrantLock();
private final AtomicBoolean halfClosed = new AtomicBoolean(false);

/**
Expand Down Expand Up @@ -100,15 +101,13 @@ public void onCompleted() {
}

private void inLock(Runnable action) {
while (!lock.compareAndSet(false, true)) {
Thread.yield();
}
try {
lock.lock();
if (!halfClosed.get()) {
action.run();
}
} finally {
lock.set(false);
lock.unlock();
}
}
}

0 comments on commit 7fe8aeb

Please sign in to comment.