Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

notify context thread listeners when the scope stack becomes empty or non-empty #4325

Merged
merged 1 commit into from
Nov 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -463,15 +463,7 @@ public void register(ContextThreadListener listener) {

@Override
protected ScopeStack initialValue() {
return new ScopeStack(
new Runnable() {
@Override
public void run() {
for (ContextThreadListener listener : listeners) {
listener.onAttach();
}
}
});
return new ScopeStack(listeners);
}

@Override
Expand All @@ -493,17 +485,16 @@ private void detach() {
*/
static final class ScopeStack {

private final Runnable onFirstUsage;
private boolean used = false;
private final List<ContextThreadListener> contextThreadListeners;
private final ArrayDeque<ContinuableScope> stack = new ArrayDeque<>(); // previous scopes

ContinuableScope top; // current scope

// set by background task when a root iteration scope remains unclosed for too long
volatile ContinuableScope overdueRootScope;

ScopeStack(Runnable onFirstUsage) {
this.onFirstUsage = onFirstUsage;
ScopeStack(List<ContextThreadListener> contextThreadListeners) {
this.contextThreadListeners = contextThreadListeners;
}

ContinuableScope active() {
Expand Down Expand Up @@ -532,13 +523,17 @@ void cleanup() {
curScope.afterActivated();
}
}
if (top == null) {
onBecomeEmpty();
}
}

/** Marks a new scope as current, pushing the previous onto the stack */
void push(final ContinuableScope scope) {
notifyOnFirstPush();
if (top != null) {
stack.push(top);
} else {
onBecomeNonEmpty();
}
top = scope;
scope.afterActivated();
Expand Down Expand Up @@ -586,10 +581,17 @@ void clear() {
top = null;
}

private void notifyOnFirstPush() {
if (!used) {
used = true;
onFirstUsage.run();
/** Notifies context thread listeners that this thread has a context now */
private void onBecomeNonEmpty() {
for (ContextThreadListener listener : contextThreadListeners) {
listener.onAttach();
}
}

/** Notifies context thread listeners that this thread no longer has a context */
private void onBecomeEmpty() {
for (ContextThreadListener listener : contextThreadListeners) {
listener.onDetach();
}
}
}
Expand Down