• 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

78.57
/temporal-sdk/src/main/java/io/temporal/internal/worker/MultiThreadedPoller.java
1
package io.temporal.internal.worker;
2

3
import com.uber.m3.tally.Scope;
4
import io.grpc.Status;
5
import io.grpc.StatusRuntimeException;
6
import io.temporal.internal.BackoffThrottler;
7
import io.temporal.internal.task.VirtualThreadDelegate;
8
import io.temporal.worker.MetricsType;
9
import io.temporal.worker.tuning.PollerBehaviorSimpleMaximum;
10
import java.util.Objects;
11
import java.util.concurrent.*;
12
import java.util.concurrent.atomic.AtomicInteger;
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15

16
/**
17
 * MultiThreadedPoller is a poller that uses multiple threads to poll tasks. It uses one thread per
18
 * poll request.
19
 */
20
final class MultiThreadedPoller<T> extends BasePoller<T> {
21

22
  public interface PollTask<TT> {
23
    /**
24
     * Pollers should shade or wrap all {@code java.lang.InterruptedException}s and raise {@code
25
     * Thread.interrupted()} flag. This follows GRPC stubs approach, see {@code
26
     * io.grpc.stub.ClientCalls#blockingUnaryCall}. Because pollers use GRPC stubs anyway, we chose
27
     * this implementation for consistency. The caller of the poll task is responsible for handling
28
     * the flag.
29
     *
30
     * @return result of the task
31
     */
32
    TT poll();
33
  }
34

35
  interface ThrowingRunnable {
36
    void run() throws Throwable;
37
  }
38

39
  private static final Logger log = LoggerFactory.getLogger(MultiThreadedPoller.class);
1 ✔
40
  private final String identity;
41
  private final PollTask<T> pollTask;
42
  private final PollerOptions pollerOptions;
43
  private final Scope workerMetricsScope;
44

45
  private Throttler pollRateThrottler;
46

47
  private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
1 ✔
48
      new PollerUncaughtExceptionHandler();
49

50
  public MultiThreadedPoller(
51
      String identity,
52
      PollTask<T> pollTask,
53
      ShutdownableTaskExecutor<T> taskExecutor,
54
      PollerOptions pollerOptions,
55
      Scope workerMetricsScope,
56
      NamespaceCapabilities namespaceCapabilities) {
57
    super(taskExecutor, namespaceCapabilities);
1 ✔
58
    Objects.requireNonNull(identity, "identity cannot be null");
1 ✔
59
    Objects.requireNonNull(pollTask, "poll service should not be null");
1 ✔
60
    Objects.requireNonNull(pollerOptions, "pollerOptions should not be null");
1 ✔
61
    Objects.requireNonNull(workerMetricsScope, "workerMetricsScope should not be null");
1 ✔
62

63
    this.identity = identity;
1 ✔
64
    this.pollTask = pollTask;
1 ✔
65
    this.pollerOptions = pollerOptions;
1 ✔
66
    this.workerMetricsScope = workerMetricsScope;
1 ✔
67
  }
1 ✔
68

69
  @Override
70
  public boolean start() {
71
    log.debug("start: {}", this);
1 ✔
72

73
    if (pollerOptions.getMaximumPollRatePerSecond() > 0.0) {
1 !
74
      pollRateThrottler =
×
75
          new Throttler(
76
              "poller",
77
              pollerOptions.getMaximumPollRatePerSecond(),
×
78
              pollerOptions.getMaximumPollRateIntervalMilliseconds());
×
79
    }
80

81
    if (!(pollerOptions.getPollerBehavior() instanceof PollerBehaviorSimpleMaximum)) {
1 !
82
      throw new IllegalArgumentException(
×
83
          "PollerBehavior "
84
              + pollerOptions.getPollerBehavior()
×
85
              + " is not supported. Only PollerBehaviorSimpleMaximum is supported.");
86
    }
87
    PollerBehaviorSimpleMaximum pollerBehavior =
1 ✔
88
        (PollerBehaviorSimpleMaximum) pollerOptions.getPollerBehavior();
1 ✔
89

90
    // If virtual threads are enabled, we use a virtual thread executor.
91
    if (pollerOptions.isUsingVirtualThreads()) {
1 !
92
      AtomicInteger threadIndex = new AtomicInteger();
×
93
      pollExecutor =
×
94
          VirtualThreadDelegate.newVirtualThreadExecutor(
×
95
              (t) -> {
96
                // TODO: Consider using a more descriptive name for the thread.
97
                t.setName(
×
98
                    pollerOptions.getPollThreadNamePrefix() + ": " + threadIndex.incrementAndGet());
×
99
                t.setUncaughtExceptionHandler(uncaughtExceptionHandler);
×
100
              });
×
101
    } else {
×
102
      // It is important to pass blocking queue of at least options.getPollThreadCount() capacity.
103
      // As task enqueues next task the buffering is needed to queue task until the previous one
104
      // releases a thread.
105
      ThreadPoolExecutor threadPoolPoller =
1 ✔
106
          new ThreadPoolExecutor(
107
              pollerBehavior.getMaxConcurrentTaskPollers(),
1 ✔
108
              pollerBehavior.getMaxConcurrentTaskPollers(),
1 ✔
109
              1,
110
              TimeUnit.SECONDS,
111
              new ArrayBlockingQueue<>(pollerBehavior.getMaxConcurrentTaskPollers()));
1 ✔
112
      threadPoolPoller.setThreadFactory(
1 ✔
113
          new ExecutorThreadFactory(
114
              pollerOptions.getPollThreadNamePrefix(),
1 ✔
115
              pollerOptions.getUncaughtExceptionHandler()));
1 ✔
116
      pollExecutor = threadPoolPoller;
1 ✔
117
    }
118

119
    for (int i = 0; i < pollerBehavior.getMaxConcurrentTaskPollers(); i++) {
1 ✔
120
      pollExecutor.execute(new PollLoopTask(new PollExecutionTask()));
1 ✔
121
      workerMetricsScope.counter(MetricsType.POLLER_START_COUNTER).inc(1);
1 ✔
122
    }
123

124
    return true;
1 ✔
125
  }
126

127
  @Override
128
  public String toString() {
129
    // TODO using pollThreadNamePrefix here is ugly. We should consider introducing some concept of
130
    // WorkerContext [workerIdentity, namespace, queue, local/non-local if applicable] and pass it
131
    // around
132
    // that will simplify such kind of logging through workers.
133
    return String.format(
1 ✔
134
        "MultiThreadedPoller{name=%s, identity=%s}",
135
        pollerOptions.getPollThreadNamePrefix(), identity);
1 ✔
136
  }
137

138
  private class PollLoopTask implements Runnable {
139

140
    private final MultiThreadedPoller.ThrowingRunnable task;
141
    private final BackoffThrottler pollBackoffThrottler;
142

143
    PollLoopTask(MultiThreadedPoller.ThrowingRunnable task) {
1 ✔
144
      this.task = task;
1 ✔
145
      this.pollBackoffThrottler =
1 ✔
146
          new BackoffThrottler(
147
              pollerOptions.getBackoffInitialInterval(),
1 ✔
148
              pollerOptions.getBackoffCongestionInitialInterval(),
1 ✔
149
              pollerOptions.getBackoffMaximumInterval(),
1 ✔
150
              pollerOptions.getBackoffCoefficient(),
1 ✔
151
              pollerOptions.getBackoffMaximumJitterCoefficient());
1 ✔
152
    }
1 ✔
153

154
    @Override
155
    public void run() {
156
      try {
157
        long throttleMs = pollBackoffThrottler.getSleepTime();
1 ✔
158
        if (throttleMs > 0) {
1 ✔
159
          Thread.sleep(throttleMs);
1 ✔
160
        }
161
        if (pollRateThrottler != null) {
1 !
162
          pollRateThrottler.throttle();
×
163
        }
164

165
        CountDownLatch suspender = suspendLatch.get();
1 ✔
166
        if (suspender != null) {
1 ✔
167
          if (log.isDebugEnabled()) {
1 !
168
            log.debug("poll task suspending latchCount=" + suspender.getCount());
×
169
          }
170
          suspender.await();
1 ✔
171
        }
172

173
        if (shouldTerminate()) {
1 !
UNCOV
174
          return;
×
175
        }
176

177
        task.run();
1 ✔
178
        pollBackoffThrottler.success();
1 ✔
179
      } catch (Throwable e) {
1 ✔
180
        if (e instanceof InterruptedException) {
1 ✔
181
          // we restore the flag here, so it can be checked and processed (with exit) in finally.
182
          Thread.currentThread().interrupt();
1 ✔
183
        } else {
184
          // Don't increase throttle on InterruptedException
185
          pollBackoffThrottler.failure(
1 ✔
186
              (e instanceof StatusRuntimeException)
1 !
187
                  ? ((StatusRuntimeException) e).getStatus().getCode()
1 ✔
188
                  : Status.Code.UNKNOWN);
×
189
        }
190
        uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), e);
1 ✔
191
      } finally {
192
        if (!shouldTerminate()) {
1 ✔
193
          // Resubmit itself back to pollExecutor
194
          pollExecutor.execute(this);
1 ✔
195
        } else {
196
          log.debug(
1 ✔
197
              "poll loop is terminated: {}",
198
              MultiThreadedPoller.this.pollTask.getClass().getSimpleName());
1 ✔
199
        }
200
      }
201
    }
1 ✔
202
  }
203

204
  private class PollExecutionTask implements MultiThreadedPoller.ThrowingRunnable {
1 ✔
205

206
    @Override
207
    public void run() throws Exception {
208
      T task = pollTask.poll();
1 ✔
209
      if (task != null) {
1 ✔
210
        taskExecutor.process(task);
1 ✔
211
      }
212
    }
1 ✔
213
  }
214
}
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