Skip to content

Commit

Permalink
Use ReentrantLock i.o. Thread#yield
Browse files Browse the repository at this point in the history
Use ReentrantLock i.o. Thread#yield. This should provide a more
efficient process for dealing with the request stream. We've seen some
users hit high CPU load specifically on the yield operation, which may
occur when a large number of query updates are passed along from one
application.

#enhancement/reentrant-lock-io-yield
  • Loading branch information
smcvb committed Oct 21, 2024
1 parent 8f915e2 commit 26410f4
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 26410f4

Please sign in to comment.