• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

temporalio / sdk-java / #433

20 Nov 2026 11:28PM UTC coverage: 71.886% (+0.05%) from 71.837%
#433

push

github

web-flow
Report storage driver types in worker heartbeats (#3230)

8791 of 14383 branches covered (61.12%)

Branch coverage included in aggregate %.

9 of 9 new or added lines in 1 file covered. (100.0%)

146 existing lines in 21 files now uncovered.

34692 of 46106 relevant lines covered (75.24%)

0.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.09
/temporal-sdk/src/main/java/io/temporal/internal/sync/DeterministicRunnerImpl.java
1
package io.temporal.internal.sync;
2

3
import com.google.common.base.Preconditions;
4
import com.google.common.primitives.Ints;
5
import io.temporal.common.context.ContextPropagator;
6
import io.temporal.internal.WorkflowThreadMarker;
7
import io.temporal.internal.common.SdkFlag;
8
import io.temporal.internal.context.ContextThreadLocal;
9
import io.temporal.internal.worker.WorkflowExecutorCache;
10
import io.temporal.serviceclient.CheckedExceptionWrapper;
11
import io.temporal.workflow.Promise;
12
import java.util.ArrayList;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.Iterator;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Optional;
19
import java.util.Set;
20
import java.util.TreeSet;
21
import java.util.concurrent.*;
22
import java.util.concurrent.locks.Lock;
23
import java.util.concurrent.locks.ReentrantLock;
24
import java.util.function.Supplier;
25
import javax.annotation.Nonnull;
26
import javax.annotation.Nullable;
27
import org.slf4j.Logger;
28
import org.slf4j.LoggerFactory;
29

30
/**
31
 * Throws Error in case of any unexpected condition. It is to fail a workflow task, not a workflow.
32
 */
33
class DeterministicRunnerImpl implements DeterministicRunner {
34

35
  private static final int ROOT_THREAD_PRIORITY = 0;
36
  private static final int CALLBACK_THREAD_PRIORITY = 10;
37
  private static final int WORKFLOW_THREAD_PRIORITY = 20000000;
38

39
  static final String WORKFLOW_ROOT_THREAD_NAME = "workflow-root";
40

41
  private static final Logger log = LoggerFactory.getLogger(DeterministicRunnerImpl.class);
1 ✔
42
  private static final ThreadLocal<WorkflowThread> currentThreadThreadLocal = new ThreadLocal<>();
1 ✔
43

44
  // Runner Lock is taken shortly by Workflow Threads when they resume and yield.
45
  // It's taken and retained also by DeterministicRunnerImpl control code.
46
  // This ensures happens-before between all workflow threads and DeterministicRunnerImpl control
47
  // code.
48
  // Note that the Runner Lock is not retained when workflow thread executes and not inside yield
49
  // method.
50
  // To check for an active event loop, inRunUntilAllBlocked value taken under Runner Lock should be
51
  // used.
52
  private final Lock lock = new ReentrantLock();
1 ✔
53
  // true when the control code of the main workflow event loop is running.
54
  // Workflow methods may get unblocked and executed by the control code when true.
55
  // Updated always with Runner Lock taken.
56
  private boolean inRunUntilAllBlocked;
57

58
  // Note that threads field is a set. So we need to make sure that getPriority never returns the
59
  // same value for different threads. We use addedThreads variable for this. Protected by lock
60
  private final Set<WorkflowThread> threads =
1 ✔
61
      new TreeSet<>((t1, t2) -> Ints.compare(t1.getPriority(), t2.getPriority()));
1 ✔
62
  // Values from RunnerLocalInternal
63
  private final Map<RunnerLocalInternal<?>, Object> runnerLocalMap = new HashMap<>();
1 ✔
64
  private final Runnable rootRunnable;
65
  private final WorkflowThreadExecutor workflowThreadExecutor;
66
  private final SyncWorkflowContext workflowContext;
67
  private final WorkflowExecutorCache cache;
68

69
  // always accessed under the runner lock
70
  private final List<NamedRunnable> toExecuteInWorkflowThread = new ArrayList<>();
1 ✔
71

72
  // Access to workflowThreadsToAdd, callbackThreadsToAdd, addedThreads doesn't have to be
73
  // synchronized.
74
  // Inside DeterministicRunner the access to these variables is under the runner lock.
75
  //
76
  // newWorkflowThread can be called from the workflow thread directly by using an Async.
77
  // But Workflow Threads when resuming or yielding are required to get the same runner lock as the
78
  // DeterministicRunner itself, which provides happens-before and guarantees visibility of changes
79
  // to these collections.
80
  // Only one Workflow Thread can run at a time and no DeterministicRunner code modifying these
81
  // variables run at the same time with the Workflow Thread.
82
  private final List<WorkflowThread> workflowThreadsToAdd = new ArrayList<>();
1 ✔
83
  private final List<WorkflowThread> callbackThreadsToAdd = new ArrayList<>();
1 ✔
84
  private int addedThreads;
85

86
  /**
87
   * Close is requested by the workflow code and the workflow thread itself. Such close is processed
88
   * immediately after the requesting thread is blocked, other workflow threads don't get a chance
89
   * to proceed after it.
90
   */
91
  private boolean exitRequested;
92

93
  /**
94
   * Close is requested by the control code. This close is potentially delayed and wait till the
95
   * workflow code is blocked if it's currently processing.
96
   */
97
  private boolean closeRequested;
98

99
  /**
100
   * true if some thread already started performing closure. Only one thread can do it and only
101
   * once.
102
   */
103
  private boolean closeStarted;
104

105
  /** If this future is filled, the runner is successfully closed */
106
  private final CompletableFuture<?> closeFuture = new CompletableFuture<>();
1 ✔
107

108
  static WorkflowThread currentThreadInternal() {
109
    WorkflowThread result = currentThreadThreadLocal.get();
1 ✔
110
    if (result == null) {
1 !
111
      throw new Error("Called from non workflow or workflow callback thread");
×
112
    }
113
    return result;
1 ✔
114
  }
115

116
  static Optional<WorkflowThread> currentThreadInternalIfPresent() {
117
    WorkflowThread result = currentThreadThreadLocal.get();
1 ✔
118
    if (result == null) {
1 ✔
119
      return Optional.empty();
1 ✔
120
    }
121
    return Optional.of(result);
1 ✔
122
  }
123

124
  static void setCurrentThreadInternal(WorkflowThread coroutine) {
125
    if (coroutine != null) {
1 ✔
126
      currentThreadThreadLocal.set(coroutine);
1 ✔
127
      WorkflowThreadMarkerAccessor.markAsWorkflowThread();
1 ✔
128
    } else {
129
      currentThreadThreadLocal.set(null);
1 ✔
130
      WorkflowThreadMarkerAccessor.markAsNonWorkflowThread();
1 ✔
131
    }
132
  }
1 ✔
133

134
  /**
135
   * Used to check for failedPromises that contain an error, but never where accessed. It is to
136
   * avoid failure swallowing by failedPromises which is very hard to troubleshoot.
137
   */
138
  private final Set<Promise<?>> failedPromises = new HashSet<>();
1 ✔
139

140
  private WorkflowThread rootWorkflowThread;
141
  private final CancellationScopeImpl runnerCancellationScope;
142

143
  DeterministicRunnerImpl(
144
      WorkflowThreadExecutor workflowThreadExecutor,
145
      @Nonnull SyncWorkflowContext workflowContext,
146
      Runnable root) {
147
    this(workflowThreadExecutor, workflowContext, root, null);
1 ✔
148
  }
1 ✔
149

150
  DeterministicRunnerImpl(
151
      WorkflowThreadExecutor workflowThreadExecutor,
152
      @Nonnull SyncWorkflowContext workflowContext,
153
      Runnable root,
154
      WorkflowExecutorCache cache) {
1 ✔
155
    this.workflowThreadExecutor = workflowThreadExecutor;
1 ✔
156
    this.workflowContext = Preconditions.checkNotNull(workflowContext, "workflowContext");
1 ✔
157
    // TODO this should be refactored, publishing of this in an constructor into external objects is
158
    // a bad practice
159
    this.workflowContext.setRunner(this);
1 ✔
160
    this.cache = cache;
1 ✔
161
    boolean deterministicCancellationScopeOrder =
1 ✔
162
        workflowContext
163
            .getReplayContext()
1 ✔
164
            .tryUseSdkFlag(SdkFlag.DETERMINISTIC_CANCELLATION_SCOPE_ORDER);
1 ✔
165
    this.runnerCancellationScope =
1 ✔
166
        new CancellationScopeImpl(true, deterministicCancellationScopeOrder, null, null);
167
    this.rootRunnable = root;
1 ✔
168
  }
1 ✔
169

170
  @Override
171
  public void runUntilAllBlocked(long deadlockDetectionTimeout) {
172
    if (rootWorkflowThread == null) {
1 ✔
173
      rootWorkflowThread = newRootThread(rootRunnable);
1 ✔
174
      threads.add(rootWorkflowThread);
1 ✔
175
      rootWorkflowThread.start();
1 ✔
176
    }
177
    lock.lock();
1 ✔
178
    try {
179
      checkNotClosed();
1 ✔
180
      checkNotCloseRequestedLocked();
1 ✔
181
      inRunUntilAllBlocked = true;
1 ✔
182
      // Keep repeating until at least one of the threads makes progress.
183
      boolean progress;
184
      outerLoop:
185
      do {
186
        if (exitRequested) {
1 !
187
          closeRequested = true;
×
188
          break;
×
189
        }
190
        if (!toExecuteInWorkflowThread.isEmpty()) {
1 ✔
191
          for (NamedRunnable nr : toExecuteInWorkflowThread) {
1 ✔
192
            Object callbackThread =
1 ✔
193
                workflowContext
194
                    .getWorkflowInboundInterceptor()
1 ✔
195
                    .newCallbackThread(nr.runnable, nr.name);
1 ✔
196
            Preconditions.checkState(
1 !
197
                callbackThread != null,
198
                "[BUG] One of the custom interceptors illegally overrode newCallbackThread result to null. "
199
                    + "Check WorkflowInboundCallsInterceptor#newCallbackThread contract.");
200
            Preconditions.checkState(
1 ✔
201
                callbackThread instanceof WorkflowThread,
202
                "[BUG] One of the custom interceptors illegally overrode newCallbackThread result. "
203
                    + "Check WorkflowInboundCallsInterceptor#newCallbackThread contract. "
204
                    + "Illegal object returned from the interceptors chain: %s",
205
                callbackThread);
206
          }
1 ✔
207

208
          appendCallbackThreadsLocked();
1 ✔
209
        }
210
        toExecuteInWorkflowThread.clear();
1 ✔
211
        progress = false;
1 ✔
212
        Iterator<WorkflowThread> ci = threads.iterator();
1 ✔
213
        while (ci.hasNext()) {
1 ✔
214
          WorkflowThread c = ci.next();
1 ✔
215
          progress = c.runUntilBlocked(deadlockDetectionTimeout) || progress;
1 ✔
216
          if (exitRequested) {
1 ✔
217
            closeRequested = true;
1 ✔
218
            break outerLoop;
1 ✔
219
          }
220
          if (c.isDone()) {
1 ✔
221
            ci.remove();
1 ✔
222
            Throwable unhandledException = c.getUnhandledException();
1 ✔
223
            if (unhandledException != null) {
1 ✔
224
              closeRequested = true;
1 ✔
225
              throw WorkflowInternal.wrap(unhandledException);
1 ✔
226
            }
227
          }
228
        }
1 ✔
229
        appendWorkflowThreadsLocked();
1 ✔
230
      } while (progress && !threads.isEmpty());
1 ✔
231
    } catch (PotentialDeadlockException e) {
1 ✔
232
      String triggerThreadStackTrace = "";
1 ✔
233
      StringBuilder otherThreadsDump = new StringBuilder();
1 ✔
234
      for (WorkflowThread t : threads) {
1 ✔
235
        if (t.getWorkflowThreadContext() != e.getWorkflowThreadContext()) {
1 ✔
236
          if (otherThreadsDump.length() > 0) {
1 !
237
            otherThreadsDump.append("\n");
×
238
          }
239
          otherThreadsDump.append(t.getStackTrace());
1 ✔
240
        } else {
241
          triggerThreadStackTrace = t.getStackTrace();
1 ✔
242
        }
243
      }
1 ✔
244
      e.setStackDump(
1 ✔
245
          triggerThreadStackTrace, otherThreadsDump.toString(), System.currentTimeMillis());
1 ✔
246
      throw e;
1 ✔
247
    } finally {
248
      inRunUntilAllBlocked = false;
1 ✔
249
      lock.unlock();
1 ✔
250
      // Close was requested while running
251
      if (closeRequested) {
1 ✔
252
        close(true);
1 ✔
253
      }
254
    }
255
  }
1 ✔
256

257
  @Override
258
  public boolean isDone() {
259
    lock.lock();
1 ✔
260
    try {
261
      return closeFuture.isDone()
1 !
262
          // if close is requested, we should wait for the closeFuture to be filled
263
          || !closeRequested && !areThreadsToBeExecuted();
1 ✔
264
    } finally {
265
      lock.unlock();
1 ✔
266
    }
267
  }
268

269
  @Override
270
  public void cancel(String reason) {
271
    executeInWorkflowThread("cancel workflow callback", () -> rootWorkflowThread.cancel(reason));
1 ✔
272
  }
1 ✔
273

274
  @Override
275
  public void close() {
276
    close(false);
1 ✔
277
  }
1 ✔
278

279
  /**
280
   * Destroys all controlled workflow threads by throwing {@link DestroyWorkflowThreadError} from
281
   * {@link WorkflowThreadContext#yield(String, Supplier)} when the threads are blocking on the
282
   * temporal-sdk code.
283
   */
284
  private void close(boolean fromWorkflowThread) {
285
    lock.lock();
1 ✔
286
    if (closeFuture.isDone()) {
1 ✔
287
      lock.unlock();
1 ✔
288
      return;
1 ✔
289
    }
290
    closeRequested = true;
1 ✔
291
    if (
1 ✔
292
    // If runUntilAllBlocked is true, event loop and workflow threads are executing.
293
    // Do not close immediately in this case.
294
    // closeRequested set earlier will make an event loop control thread to call close()
295
    // at the end that will actually perform the closure.
296
    inRunUntilAllBlocked
297
        // some other thread or caller is already in the process of closing
298
        || closeStarted) {
299

300
      lock.unlock();
1 ✔
301
      // If called from the workflow thread, we don't want to block this call, otherwise we
302
      // will cause a deadlock. The thread performing the closure waits for all workflow threads
303
      // to complete first.
304
      if (!fromWorkflowThread) {
1 ✔
305
        // We will not perform the closure in this call and should just wait on the future when
306
        // another thread responsible for it will close.
307
        closeFuture.join();
1 ✔
308
      }
309
      return;
1 ✔
310
    }
311

312
    closeStarted = true;
1 ✔
313
    // lock is taken here
314
    try {
315
      // in some circumstances when a workflow broke Deadline Detector,
316
      // runUntilAllBlocked may return while workflow threads are still running.
317
      // If this happens, these threads may potentially start new additional threads that will be
318
      // in workflowThreadsToAdd and callbackThreadsToAdd.
319
      // That's why we need to make sure that all the spawned threads were shut down in a cycle.
320
      while (areThreadsToBeExecuted()) {
1 ✔
321
        List<WorkflowThreadStopFuture> threadFutures = new ArrayList<>();
1 ✔
322
        try {
323
          toExecuteInWorkflowThread.clear();
1 ✔
324
          appendWorkflowThreadsLocked();
1 ✔
325
          appendCallbackThreadsLocked();
1 ✔
326
          for (WorkflowThread workflowThread : threads) {
1 ✔
327
            threadFutures.add(
1 ✔
328
                new WorkflowThreadStopFuture(workflowThread, workflowThread.stopNow()));
1 ✔
329
          }
1 ✔
330
          threads.clear();
1 ✔
331

332
          // We cannot use an iterator to unregister failed Promises since f.get()
333
          // will remove the promise directly from failedPromises. This causes an
334
          // ConcurrentModificationException
335
          // For this reason we will loop over a copy of failedPromises.
336
          Set<Promise<?>> failedPromisesLoop = new HashSet<>(failedPromises);
1 ✔
337
          for (Promise<?> f : failedPromisesLoop) {
1 ✔
338
            try {
339
              f.get();
×
340
              throw new Error("unreachable");
×
341
            } catch (RuntimeException e) {
1 ✔
342
              log.warn(
1 ✔
343
                  "Promise completed with exception and was never accessed. The ignored exception:",
344
                  CheckedExceptionWrapper.unwrap(e));
1 ✔
345
            }
346
          }
1 ✔
347
        } finally {
348
          // we need to unlock for the further code because threads will not be able to proceed with
349
          // destruction otherwise.
350
          lock.unlock();
1 ✔
351
        }
352

353
        // Wait on all tasks outside the lock since these tasks use the same lock to execute.
354
        try {
355
          for (WorkflowThreadStopFuture threadFuture : threadFutures) {
1 ✔
356
            try {
357
              threadFuture.stopFuture.get(10, TimeUnit.SECONDS);
1 ✔
358
            } catch (TimeoutException e) {
×
359
              WorkflowThread workflowThread = threadFuture.workflowThread;
×
360
              log.error(
×
361
                  "[BUG] Workflow thread '{}' of workflow '{}' can't be destroyed in time. "
362
                      + "This will lead to a workflow cache leak. "
363
                      + "This problem is usually caused by a workflow implementation swallowing java.lang.Error instead of rethrowing it. "
364
                      + " Thread dump of the stuck thread:\n{}",
365
                  workflowThread.getName(),
×
366
                  workflowContext.getReplayContext().getWorkflowId(),
×
367
                  workflowThread.getStackTrace());
×
368
            }
1 ✔
369
          }
1 ✔
370
        } catch (InterruptedException e) {
1 ✔
371
          Thread.currentThread().interrupt();
1 ✔
372
          // Worker is likely stopped with shutdownNow()
373
          // TODO consider propagating as an original interrupted exception to the top level
374
          throw new Error("Worker executor thread interrupted during stopping of a coroutine", e);
1 ✔
375
        } catch (ExecutionException e) {
×
376
          throw new Error("[BUG] Unexpected failure while stopping a coroutine", e);
×
377
        } finally {
378
          // acquire the lock back as it should be taken for the loop condition check.
379
          lock.lock();
1 ✔
380
        }
381
      }
1 ✔
382
    } finally {
383
      closeFuture.complete(null);
1 ✔
384
      lock.unlock();
1 ✔
385
    }
386
  }
1 ✔
387

388
  @Override
389
  public String stackTrace() {
390
    StringBuilder result = new StringBuilder();
1 ✔
391
    lock.lock();
1 ✔
392
    try {
393
      if (closeFuture.isDone()) {
1 ✔
394
        return "Workflow is closed.";
1 ✔
395
      }
396
      for (WorkflowThread coroutine : threads) {
1 ✔
397
        if (result.length() > 0) {
1 ✔
398
          result.append("\n");
1 ✔
399
        }
400
        coroutine.addStackTrace(result);
1 ✔
401
      }
1 ✔
402
    } finally {
403
      lock.unlock();
1 ✔
404
    }
405
    return result.toString();
1 ✔
406
  }
407

408
  private void appendWorkflowThreadsLocked() {
409
    threads.addAll(workflowThreadsToAdd);
1 ✔
410
    workflowThreadsToAdd.clear();
1 ✔
411
  }
1 ✔
412

413
  private void appendCallbackThreadsLocked() {
414
    // TODO I'm not sure this comment makes sense, because threads list has comparator and we use
415
    // thread priorities anyway.
416

417
    // It is important to prepend threads as there are callbacks
418
    // like signals that have to run before any other threads.
419
    // Otherwise signal might be never processed if it was received
420
    // after workflow decided to close.
421
    // Adding the callbacks in the same order as they appear in history.
422
    for (int i = callbackThreadsToAdd.size() - 1; i >= 0; i--) {
1 ✔
423
      threads.add(callbackThreadsToAdd.get(i));
1 ✔
424
    }
425
    callbackThreadsToAdd.clear();
1 ✔
426
  }
1 ✔
427

428
  /** Creates a new instance of a root workflow thread. */
429
  private WorkflowThread newRootThread(Runnable runnable) {
430
    String name = WORKFLOW_ROOT_THREAD_NAME;
1 ✔
431
    // TODO: workflow instance specific thread name
432
    // String name = "workflow[" + workflowContext.getContext().getWorkflowId() + "]-root";
433
    if (rootWorkflowThread != null) {
1 !
434
      throw new IllegalStateException(
×
435
          "newRootThread can be called only if there is no existing root workflow thread");
436
    }
437
    rootWorkflowThread =
1 ✔
438
        new RootWorkflowThreadImpl(
439
            workflowThreadExecutor,
440
            workflowContext,
441
            this,
442
            name,
443
            ROOT_THREAD_PRIORITY,
444
            false,
445
            runnerCancellationScope,
446
            EventGroupScope.EMPTY,
447
            runnable,
448
            cache,
449
            getContextPropagators(),
1 ✔
450
            getPropagatedContexts());
1 ✔
451
    return rootWorkflowThread;
1 ✔
452
  }
453

454
  @Nonnull
455
  @Override
456
  public WorkflowThread newWorkflowThread(
457
      Runnable runnable, boolean detached, @Nullable String name) {
458
    if (name == null) {
1 ✔
459
      name = "workflow[" + workflowContext.getReplayContext().getWorkflowId() + "]-" + addedThreads;
1 ✔
460
    }
461
    if (rootWorkflowThread == null) {
1 !
UNCOV
462
      throw new IllegalStateException(
×
463
          "newChildThread can be called only with existing root workflow thread");
464
    }
465
    checkWorkflowThreadOnly();
1 ✔
466
    checkNotClosed();
1 ✔
467
    WorkflowThread result =
1 ✔
468
        new WorkflowThreadImpl(
469
            workflowThreadExecutor,
470
            workflowContext,
471
            this,
472
            name,
473
            WORKFLOW_THREAD_PRIORITY + (addedThreads++),
474
            detached,
475
            CancellationScopeImpl.current(),
1 ✔
476
            EventGroupScope.current(),
1 ✔
477
            runnable,
478
            cache,
479
            getContextPropagators(),
1 ✔
480
            getPropagatedContexts());
1 ✔
481
    workflowThreadsToAdd.add(result);
1 ✔
482
    return result;
1 ✔
483
  }
484

485
  @Nonnull
486
  @Override
487
  public WorkflowThread newCallbackThread(Runnable runnable, @Nullable String name) {
488
    if (name == null) {
1 !
UNCOV
489
      name = "workflow[" + workflowContext.getReplayContext().getWorkflowId() + "]-" + addedThreads;
×
490
    }
491
    WorkflowThread result =
1 ✔
492
        new WorkflowThreadImpl(
493
            workflowThreadExecutor,
494
            workflowContext,
495
            this,
496
            name,
497
            CALLBACK_THREAD_PRIORITY
498
                + (addedThreads++), // maintain the order in toExecuteInWorkflowThread
499
            false,
500
            runnerCancellationScope,
501
            EventGroupScope.EMPTY,
502
            runnable,
503
            cache,
504
            getContextPropagators(),
1 ✔
505
            getPropagatedContexts());
1 ✔
506
    callbackThreadsToAdd.add(result);
1 ✔
507
    return result;
1 ✔
508
  }
509

510
  /**
511
   * Executes before any other threads next time runUntilBlockedCalled. Must never be called from
512
   * any workflow threads.
513
   */
514
  @Override
515
  public void executeInWorkflowThread(String name, Runnable runnable) {
516
    lock.lock();
1 ✔
517
    try {
518
      // if the execution is closed, we will just add the callbacks, but we will never create
519
      // threads for them, so they will be effectively ignored
520
      toExecuteInWorkflowThread.add(new NamedRunnable(name, runnable));
1 ✔
521
    } finally {
522
      lock.unlock();
1 ✔
523
    }
524
  }
1 ✔
525

526
  Lock getLock() {
527
    return lock;
1 ✔
528
  }
529

530
  /** Register a promise that had failed but wasn't accessed yet. */
531
  void registerFailedPromise(Promise<?> promise) {
532
    if (!promise.isCompleted()) {
1 !
UNCOV
533
      throw new Error("expected failed");
×
534
    }
535
    failedPromises.add(promise);
1 ✔
536
  }
1 ✔
537

538
  /** Forget a failed promise as it was accessed. */
539
  void forgetFailedPromise(Promise<?> promise) {
540
    failedPromises.remove(promise);
1 ✔
541
  }
1 ✔
542

543
  void exit() {
544
    checkNotClosed();
1 ✔
545
    checkWorkflowThreadOnly();
1 ✔
546
    this.exitRequested = true;
1 ✔
547
  }
1 ✔
548

549
  private void checkWorkflowThreadOnly() {
550
    // TODO this is not a correct way to test for the fact that the method is called from the
551
    // workflow method.
552
    //  This check verifies that the workflow methods or controlling code are now running,
553
    //  but it doesn't verify if the calling thread is the one.
554
    if (!inRunUntilAllBlocked) {
1 ✔
555
      throw new Error("called from non workflow thread");
1 ✔
556
    }
557
  }
1 ✔
558

559
  private void checkNotCloseRequestedLocked() {
560
    if (closeRequested) {
1 ✔
561
      throw new Error("close requested");
1 ✔
562
    }
563
  }
1 ✔
564

565
  private void checkNotClosed() {
566
    if (closeFuture.isDone()) {
1 !
UNCOV
567
      throw new Error("closed");
×
568
    }
569
  }
1 ✔
570

571
  /**
572
   * @return true if there are no threads left to be processed for this workflow.
573
   */
574
  private boolean areThreadsToBeExecuted() {
575
    return !threads.isEmpty()
1 ✔
576
        || !workflowThreadsToAdd.isEmpty()
1 !
577
        || !callbackThreadsToAdd.isEmpty()
1 !
578
        || !toExecuteInWorkflowThread.isEmpty();
1 ✔
579
  }
580

581
  /**
582
   * Retrieve data from runner locals. Returns 1. not found (an empty Optional) 2. found but null
583
   * (an Optional of an empty Optional) 3. found and non-null (an Optional of an Optional of a
584
   * value). The type nesting is because Java Optionals cannot understand "Some null" vs "None",
585
   * which is exactly what we need here.
586
   *
587
   * @param key
588
   * @return one of three cases
589
   * @param <T>
590
   */
591
  @SuppressWarnings("unchecked")
592
  public <T> Optional<Optional<T>> getRunnerLocal(RunnerLocalInternal<T> key) {
593
    if (!runnerLocalMap.containsKey(key)) {
1 ✔
594
      return Optional.empty();
1 ✔
595
    }
596
    return Optional.of(Optional.ofNullable((T) runnerLocalMap.get(key)));
1 ✔
597
  }
598

599
  <T> void setRunnerLocal(RunnerLocalInternal<T> key, T value) {
600
    runnerLocalMap.put(key, value);
1 ✔
601
  }
1 ✔
602

603
  /**
604
   * If we're executing as part of a workflow, get the current thread's context. Otherwise get the
605
   * context info from the workflow context.
606
   */
607
  private Map<String, Object> getPropagatedContexts() {
608
    if (currentThreadThreadLocal.get() != null) {
1 ✔
609
      return ContextThreadLocal.getCurrentContextForPropagation();
1 ✔
610
    } else {
611
      return workflowContext.getPropagatedContexts();
1 ✔
612
    }
613
  }
614

615
  private List<ContextPropagator> getContextPropagators() {
616
    if (currentThreadThreadLocal.get() != null) {
1 ✔
617
      return ContextThreadLocal.getContextPropagators();
1 ✔
618
    } else {
619
      return workflowContext.getContextPropagators();
1 ✔
620
    }
621
  }
622

623
  private static class WorkflowThreadMarkerAccessor extends WorkflowThreadMarker {
624
    public static void markAsWorkflowThread() {
625
      isWorkflowThreadThreadLocal.set(true);
1 ✔
626
    }
1 ✔
627

628
    public static void markAsNonWorkflowThread() {
629
      isWorkflowThreadThreadLocal.set(false);
1 ✔
630
    }
1 ✔
631
  }
632

633
  private static class NamedRunnable {
634
    private final String name;
635
    private final Runnable runnable;
636

637
    private NamedRunnable(String name, Runnable runnable) {
1 ✔
638
      this.name = name;
1 ✔
639
      this.runnable = runnable;
1 ✔
640
    }
1 ✔
641
  }
642

643
  private static class WorkflowThreadStopFuture {
644
    private final WorkflowThread workflowThread;
645
    private final Future<?> stopFuture;
646

647
    public WorkflowThreadStopFuture(WorkflowThread workflowThread, Future<?> stopFuture) {
1 ✔
648
      this.workflowThread = workflowThread;
1 ✔
649
      this.stopFuture = stopFuture;
1 ✔
650
    }
1 ✔
651
  }
652
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc