• 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

75.12
/temporal-sdk/src/main/java/io/temporal/internal/sync/WorkflowThreadImpl.java
1
package io.temporal.internal.sync;
2

3
import com.google.common.base.Preconditions;
4
import io.temporal.common.context.ContextPropagator;
5
import io.temporal.failure.CanceledFailure;
6
import io.temporal.internal.common.NonIdempotentHandle;
7
import io.temporal.internal.common.SdkFlag;
8
import io.temporal.internal.context.ContextThreadLocal;
9
import io.temporal.internal.logging.LoggerTag;
10
import io.temporal.internal.logging.PrefixedMdc;
11
import io.temporal.internal.replay.ReplayWorkflowContext;
12
import io.temporal.internal.worker.WorkflowExecutorCache;
13
import io.temporal.workflow.Functions;
14
import io.temporal.workflow.Promise;
15
import java.io.PrintWriter;
16
import java.io.StringWriter;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Optional;
21
import java.util.concurrent.CompletableFuture;
22
import java.util.concurrent.Future;
23
import java.util.concurrent.RejectedExecutionException;
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
import org.slf4j.MDC;
30

31
class WorkflowThreadImpl implements WorkflowThread {
32
  /**
33
   * Runnable passed to the thread that wraps a runnable passed to the WorkflowThreadImpl
34
   * constructor.
35
   */
36
  class RunnableWrapper implements Runnable {
37

38
    private final WorkflowThreadContext threadContext;
39
    // TODO: Move MDC injection logic into an interceptor as this context shouldn't be leaked
40
    // to the WorkflowThreadImpl
41
    private final ReplayWorkflowContext replayWorkflowContext;
42
    private String originalName;
43
    private String name;
44
    private final CancellationScopeImpl cancellationScope;
45
    private final EventGroupScope eventGroupScope;
46
    private final List<ContextPropagator> contextPropagators;
47
    private final Map<String, Object> propagatedContexts;
48

49
    RunnableWrapper(
50
        WorkflowThreadContext threadContext,
51
        ReplayWorkflowContext replayWorkflowContext,
52
        String name,
53
        boolean detached,
54
        CancellationScopeImpl parent,
55
        EventGroupScope eventGroupScope,
56
        Runnable runnable,
57
        List<ContextPropagator> contextPropagators,
58
        Map<String, Object> propagatedContexts) {
1 ✔
59
      this.threadContext = threadContext;
1 ✔
60
      this.replayWorkflowContext = replayWorkflowContext;
1 ✔
61
      this.name = name;
1 ✔
62
      boolean deterministicCancellationScopeOrder =
1 ✔
63
          replayWorkflowContext.checkSdkFlag(SdkFlag.DETERMINISTIC_CANCELLATION_SCOPE_ORDER);
1 ✔
64
      this.cancellationScope =
1 ✔
65
          new CancellationScopeImpl(
66
              detached, deterministicCancellationScopeOrder, runnable, parent);
67
      this.eventGroupScope = eventGroupScope;
1 ✔
68
      Preconditions.checkState(
1 ✔
69
          context.getStatus() == Status.CREATED, "threadContext not in CREATED state");
1 !
70
      this.contextPropagators = contextPropagators;
1 ✔
71
      this.propagatedContexts = propagatedContexts;
1 ✔
72
    }
1 ✔
73

74
    @Override
75
    public void run() {
76
      Thread thread = Thread.currentThread();
1 ✔
77
      originalName = thread.getName();
1 ✔
78
      thread.setName(name);
1 ✔
79

80
      threadContext.initializeCurrentThread(thread);
1 ✔
81
      DeterministicRunnerImpl.setCurrentThreadInternal(WorkflowThreadImpl.this);
1 ✔
82

83
      PrefixedMdc mdc = replayWorkflowContext.getLoggerMdc();
1 ✔
84
      mdc.put(LoggerTag.WORKFLOW_ID, replayWorkflowContext.getWorkflowId());
1 ✔
85
      mdc.put(LoggerTag.WORKFLOW_TYPE, replayWorkflowContext.getWorkflowType().getName());
1 ✔
86
      mdc.put(LoggerTag.RUN_ID, replayWorkflowContext.getRunId());
1 ✔
87
      mdc.put(LoggerTag.TASK_QUEUE, replayWorkflowContext.getTaskQueue());
1 ✔
88
      mdc.put(LoggerTag.NAMESPACE, replayWorkflowContext.getNamespace());
1 ✔
89

90
      // Repopulate the context(s)
91
      ContextThreadLocal.setContextPropagators(this.contextPropagators);
1 ✔
92
      ContextThreadLocal.propagateContextToCurrentThread(this.propagatedContexts);
1 ✔
93
      try {
94
        // initialYield blocks thread until the first runUntilBlocked is called.
95
        // Otherwise, r starts executing without control of the sync.
96
        threadContext.initialYield();
1 ✔
97
        eventGroupScope.run(cancellationScope::run);
1 ✔
98
      } catch (DestroyWorkflowThreadError e) {
1 ✔
99
        if (!threadContext.isDestroyRequested()) {
1 ✔
100
          threadContext.setUnhandledException(e);
1 ✔
101
        }
102
      } catch (Error e) {
1 ✔
103
        threadContext.setUnhandledException(e);
1 ✔
UNCOV
104
      } catch (CanceledFailure e) {
×
105
        if (!isCancelRequested()) {
×
106
          threadContext.setUnhandledException(e);
×
107
        }
UNCOV
108
        if (log.isDebugEnabled()) {
×
UNCOV
109
          log.debug(String.format("Workflow thread \"%s\" run canceled", name));
×
110
        }
111
      } catch (Throwable e) {
1 ✔
112
        threadContext.setUnhandledException(e);
1 ✔
113
      } finally {
114
        DeterministicRunnerImpl.setCurrentThreadInternal(null);
1 ✔
115
        threadContext.makeDone();
1 ✔
116
        thread.setName(originalName);
1 ✔
117
        MDC.clear();
1 ✔
118
      }
119
    }
1 ✔
120

121
    public String getName() {
122
      return name;
1 ✔
123
    }
124

125
    StackTraceElement[] getStackTrace() {
126
      @Nullable Thread thread = threadContext.getCurrentThread();
1 ✔
127
      if (thread != null) {
1 ✔
128
        return thread.getStackTrace();
1 ✔
129
      }
130
      return new StackTraceElement[0];
1 ✔
131
    }
132

133
    public void setName(String name) {
134
      this.name = name;
×
UNCOV
135
      @Nullable Thread thread = threadContext.getCurrentThread();
×
136
      if (thread != null) {
×
UNCOV
137
        thread.setName(name);
×
138
      }
UNCOV
139
    }
×
140
  }
141

142
  private static final Logger log = LoggerFactory.getLogger(WorkflowThreadImpl.class);
1 ✔
143

144
  private final WorkflowThreadExecutor workflowThreadExecutor;
145
  private final WorkflowThreadContext context;
146
  private final WorkflowExecutorCache cache;
147
  private final SyncWorkflowContext syncWorkflowContext;
148

149
  private final DeterministicRunnerImpl runner;
150
  private final RunnableWrapper task;
151
  private final int priority;
152
  private Future<?> taskFuture;
153
  private final Map<WorkflowThreadLocalInternal<?>, Object> threadLocalMap = new HashMap<>();
1 ✔
154

155
  WorkflowThreadImpl(
156
      WorkflowThreadExecutor workflowThreadExecutor,
157
      SyncWorkflowContext syncWorkflowContext,
158
      DeterministicRunnerImpl runner,
159
      @Nonnull String name,
160
      int priority,
161
      boolean detached,
162
      CancellationScopeImpl parentCancellationScope,
163
      EventGroupScope eventGroupScope,
164
      Runnable runnable,
165
      WorkflowExecutorCache cache,
166
      List<ContextPropagator> contextPropagators,
167
      Map<String, Object> propagatedContexts) {
1 ✔
168
    this.workflowThreadExecutor = workflowThreadExecutor;
1 ✔
169
    this.syncWorkflowContext = Preconditions.checkNotNull(syncWorkflowContext);
1 ✔
170
    this.runner = runner;
1 ✔
171
    this.context = new WorkflowThreadContext(runner.getLock());
1 ✔
172
    this.cache = cache;
1 ✔
173
    this.priority = priority;
1 ✔
174
    this.task =
1 ✔
175
        new RunnableWrapper(
176
            context,
177
            syncWorkflowContext.getReplayContext(),
1 ✔
178
            Preconditions.checkNotNull(name, "Thread name shouldn't be null"),
1 ✔
179
            detached,
180
            parentCancellationScope,
181
            eventGroupScope,
182
            runnable,
183
            contextPropagators,
184
            propagatedContexts);
185
  }
1 ✔
186

187
  @Override
188
  public void run() {
189
    throw new UnsupportedOperationException("not used");
×
190
  }
191

192
  @Override
193
  public boolean isDetached() {
UNCOV
194
    return task.cancellationScope.isDetached();
×
195
  }
196

197
  @Override
198
  public void cancel() {
199
    task.cancellationScope.cancel();
1 ✔
200
  }
1 ✔
201

202
  @Override
203
  public void cancel(String reason) {
204
    task.cancellationScope.cancel(reason);
1 ✔
205
  }
1 ✔
206

207
  @Override
208
  public String getCancellationReason() {
209
    return task.cancellationScope.getCancellationReason();
×
210
  }
211

212
  @Override
213
  public boolean isCancelRequested() {
214
    return task.cancellationScope.isCancelRequested();
×
215
  }
216

217
  @Override
218
  public Promise<String> getCancellationRequest() {
UNCOV
219
    return task.cancellationScope.getCancellationRequest();
×
220
  }
221

222
  @Override
223
  public void start() {
224
    context.verifyAndStart();
1 ✔
225
    while (true) {
226
      try {
227
        taskFuture = workflowThreadExecutor.submit(task);
1 ✔
228
        return;
1 ✔
229
      } catch (RejectedExecutionException e) {
1 ✔
230
        if (cache != null) {
1 ✔
231
          SyncWorkflowContext workflowContext = getWorkflowContext();
1 ✔
232
          ReplayWorkflowContext context = workflowContext.getReplayContext();
1 ✔
233
          boolean evicted =
1 ✔
234
              cache.evictAnyNotInProcessing(
1 ✔
235
                  context.getWorkflowExecution(), workflowContext.getMetricsScope());
1 ✔
236
          if (!evicted) {
1 ✔
237
            // Note here we need to throw error, not exception. Otherwise it will be
238
            // translated to workflow execution exception and instead of failing the
239
            // workflow task we will be failing the workflow.
240
            throw new WorkflowRejectedExecutionError(e);
1 ✔
241
          }
242
        } else {
1 ✔
243
          throw new WorkflowRejectedExecutionError(e);
1 ✔
244
        }
245
      }
1 ✔
246
    }
247
  }
248

249
  @Override
250
  public boolean isStarted() {
UNCOV
251
    return context.getStatus() != Status.CREATED;
×
252
  }
253

254
  @Override
255
  public WorkflowThreadContext getWorkflowThreadContext() {
256
    return context;
1 ✔
257
  }
258

259
  @Override
260
  public DeterministicRunnerImpl getRunner() {
261
    return runner;
1 ✔
262
  }
263

264
  @Override
265
  public SyncWorkflowContext getWorkflowContext() {
266
    return syncWorkflowContext;
1 ✔
267
  }
268

269
  @Override
270
  public void setName(String name) {
UNCOV
271
    task.setName(name);
×
UNCOV
272
  }
×
273

274
  @Override
275
  public String getName() {
276
    return task.getName();
1 ✔
277
  }
278

279
  @Override
280
  public long getId() {
UNCOV
281
    return hashCode();
×
282
  }
283

284
  @Override
285
  public int getPriority() {
286
    return priority;
1 ✔
287
  }
288

289
  @Override
290
  public boolean runUntilBlocked(long deadlockDetectionTimeoutMs) {
291
    if (taskFuture == null) {
1 ✔
292
      start();
1 ✔
293
    }
294
    return context.runUntilBlocked(deadlockDetectionTimeoutMs);
1 ✔
295
  }
296

297
  @Override
298
  public NonIdempotentHandle lockDeadlockDetector() {
299
    return context.lockDeadlockDetector();
1 ✔
300
  }
301

302
  @Override
303
  public boolean isDone() {
304
    return context.isDone();
1 ✔
305
  }
306

307
  @Override
308
  public Throwable getUnhandledException() {
309
    return context.getUnhandledException();
1 ✔
310
  }
311

312
  /**
313
   * Evaluates function in the threadContext of the coroutine without unblocking it. Used to get
314
   * current coroutine status, like stack trace.
315
   *
316
   * @param function Parameter is reason for current goroutine blockage.
317
   */
318
  public void evaluateInCoroutineContext(Functions.Proc1<String> function) {
UNCOV
319
    context.evaluateInCoroutineContext(function);
×
UNCOV
320
  }
×
321

322
  /**
323
   * Interrupt coroutine by throwing DestroyWorkflowThreadError from an await method it is blocked
324
   * on and return underlying Future to be waited on.
325
   */
326
  @Override
327
  public Future<?> stopNow() {
328
    // Cannot call destroy() on itself
329
    @Nullable Thread thread = context.getCurrentThread();
1 ✔
330
    if (Thread.currentThread().equals(thread)) {
1 !
UNCOV
331
      throw new Error("Cannot call destroy on itself: " + thread.getName());
×
332
    }
333
    context.initiateDestroy();
1 ✔
334
    if (taskFuture == null) {
1 ✔
335
      return getCompletedFuture();
1 ✔
336
    }
337
    return taskFuture;
1 ✔
338
  }
339

340
  private Future<?> getCompletedFuture() {
341
    CompletableFuture<String> f = new CompletableFuture<>();
1 ✔
342
    f.complete("done");
1 ✔
343
    return f;
1 ✔
344
  }
345

346
  @Override
347
  public void addStackTrace(StringBuilder result) {
348
    result.append(getName());
1 ✔
349
    @Nullable Thread thread = context.getCurrentThread();
1 ✔
350
    if (thread == null) {
1 !
UNCOV
351
      result.append("(NEW)");
×
UNCOV
352
      return;
×
353
    }
354
    result
1 ✔
355
        .append(": (BLOCKED on ")
1 ✔
356
        .append(getWorkflowThreadContext().getYieldReason())
1 ✔
357
        .append(")\n");
1 ✔
358
    // These numbers might change if implementation changes.
359
    int omitTop = 5;
1 ✔
360
    int omitBottom = 7;
1 ✔
361
    // TODO it's not a good idea to rely on the name to understand the thread type. Instead of that
362
    // we would better
363
    // assign an explicit thread type enum to the threads. This will be especially important when we
364
    // refactor
365
    // root and workflow-method
366
    // thread names into names that will include workflowId
367
    if (DeterministicRunnerImpl.WORKFLOW_ROOT_THREAD_NAME.equals(getName())) {
1 !
368
      // TODO revisit this number
UNCOV
369
      omitBottom = 11;
×
370
    } else if (getName().startsWith(WorkflowMethodThreadNameStrategy.WORKFLOW_MAIN_THREAD_PREFIX)) {
1 ✔
371
      // TODO revisit this number
372
      omitBottom = 11;
1 ✔
373
    }
374
    StackTraceElement[] stackTrace = thread.getStackTrace();
1 ✔
375
    for (int i = omitTop; i < stackTrace.length - omitBottom; i++) {
1 ✔
376
      StackTraceElement e = stackTrace[i];
1 ✔
377
      if (i == omitTop && "await".equals(e.getMethodName())) continue;
1 !
378
      result.append(e);
1 ✔
379
      result.append("\n");
1 ✔
380
    }
381
  }
1 ✔
382

383
  @Override
384
  public void yield(String reason, Supplier<Boolean> unblockCondition) {
385
    context.yield(reason, unblockCondition);
1 ✔
386
  }
1 ✔
387

388
  @Override
389
  public void exitThread() {
390
    runner.exit();
1 ✔
391
    throw new DestroyWorkflowThreadError("exit");
1 ✔
392
  }
393

394
  @Override
395
  public <T> void setThreadLocal(WorkflowThreadLocalInternal<T> key, T value) {
396
    threadLocalMap.put(key, value);
1 ✔
397
  }
1 ✔
398

399
  /**
400
   * Retrieve data from thread locals. Returns 1. not found (an empty Optional) 2. found but null
401
   * (an Optional of an empty Optional) 3. found and non-null (an Optional of an Optional of a
402
   * value). The type nesting is because Java Optionals cannot understand "Some null" vs "None",
403
   * which is exactly what we need here.
404
   *
405
   * @param key
406
   * @return one of three cases
407
   * @param <T>
408
   */
409
  @SuppressWarnings("unchecked")
410
  public <T> Optional<Optional<T>> getThreadLocal(WorkflowThreadLocalInternal<T> key) {
411
    if (!threadLocalMap.containsKey(key)) {
1 ✔
412
      return Optional.empty();
1 ✔
413
    }
414
    return Optional.of(Optional.ofNullable((T) threadLocalMap.get(key)));
1 ✔
415
  }
416

417
  /**
418
   * @return stack trace of the coroutine thread
419
   */
420
  @Override
421
  public String getStackTrace() {
422
    StackTraceElement[] st = task.getStackTrace();
1 ✔
423
    StringWriter sw = new StringWriter();
1 ✔
424
    PrintWriter pw = new PrintWriter(sw);
1 ✔
425
    pw.append(task.getName());
1 ✔
426
    pw.append("\n");
1 ✔
427
    for (StackTraceElement se : st) {
1 ✔
428
      pw.println("\tat " + se);
1 ✔
429
    }
430
    return sw.toString();
1 ✔
431
  }
432

433
  static class YieldWithTimeoutCondition implements Supplier<Boolean> {
434

435
    private final Supplier<Boolean> unblockCondition;
436
    private final long blockedUntil;
437
    private boolean timedOut;
438

UNCOV
439
    YieldWithTimeoutCondition(Supplier<Boolean> unblockCondition, long blockedUntil) {
×
440
      this.unblockCondition = unblockCondition;
×
UNCOV
441
      this.blockedUntil = blockedUntil;
×
UNCOV
442
    }
×
443

444
    boolean isTimedOut() {
UNCOV
445
      return timedOut;
×
446
    }
447

448
    /**
449
     * @return true if condition matched or timed out
450
     */
451
    @Override
452
    public Boolean get() {
453
      boolean result = unblockCondition.get();
×
454
      if (result) {
×
UNCOV
455
        return true;
×
456
      }
UNCOV
457
      long currentTimeMillis = WorkflowInternal.currentTimeMillis();
×
UNCOV
458
      timedOut = currentTimeMillis >= blockedUntil;
×
UNCOV
459
      return timedOut;
×
460
    }
461
  }
462
}
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