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

grpc / grpc-java / #20383

30 Jul 2026 04:33PM UTC coverage: 89.149% (-0.005%) from 89.154%
#20383

push

github

ejona86
api: Better explain the executors and how to configure them

38310 of 42973 relevant lines covered (89.15%)

0.89 hits per line

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

32.14
/../api/src/main/java/io/grpc/ServerBuilder.java
1
/*
2
 * Copyright 2015 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20

21
import com.google.common.base.Preconditions;
22
import java.io.File;
23
import java.io.InputStream;
24
import java.util.List;
25
import java.util.concurrent.Executor;
26
import java.util.concurrent.TimeUnit;
27
import javax.annotation.Nullable;
28

29
/**
30
 * A builder for {@link Server} instances.
31
 *
32
 * @param <T> The concrete type of this builder.
33
 * @since 1.0.0
34
 */
35
public abstract class ServerBuilder<T extends ServerBuilder<T>> {
1✔
36

37
  /**
38
   * Static factory for creating a new ServerBuilder.
39
   *
40
   * @param port the port to listen on
41
   * @since 1.0.0
42
   */
43
  public static ServerBuilder<?> forPort(int port) {
44
    return ServerProvider.provider().builderForPort(port);
1✔
45
  }
46

47
  /**
48
   * Execute application code directly in the transport thread. The application must not block under
49
   * any circumstances.
50
   *
51
   * <p>Depending on the underlying transport and the application code, using a direct executor may
52
   * lead to 10s of µs latency reduction but causes a substantial performance degradation when
53
   * misused.
54
   *
55
   * <p>Calling this method is semantically equivalent to calling {@link #executor(Executor)} and
56
   * passing in a direct executor. However, this is the preferred way as it may allow the transport
57
   * to perform special optimizations.
58
   *
59
   * @return this
60
   * @since 1.0.0
61
   */
62
  public abstract T directExecutor();
63

64
  /**
65
   * Set the default executor for service callbacks.
66
   *
67
   * <p>It's an optional parameter. If the user has not provided an executor when the server is
68
   * built, the builder will use a static cached thread pool. Users are encouraged to specify their
69
   * own executor that limits the number of threads.
70
   *
71
   * <p>The server won't take ownership of the given executor. It's caller's responsibility to
72
   * shut down the executor when it's desired.
73
   *
74
   * @return this
75
   * @since 1.0.0
76
   */
77
  public abstract T executor(@Nullable Executor executor);
78

79

80
  /**
81
   * Allows for defining a way to provide a custom executor to handle the server call.
82
   * This executor is the result of calling
83
   * {@link ServerCallExecutorSupplier#getExecutor(ServerCall, Metadata)} per RPC.
84
   *
85
   * <p>It's an optional parameter. If it is provided, the {@link #executor(Executor)} would still
86
   * run necessary tasks before the {@link ServerCallExecutorSupplier} is ready to be called, then
87
   * it switches over. But if calling {@link ServerCallExecutorSupplier} returns null, the server
88
   * call is still handled by the default {@link #executor(Executor)} as a fallback.
89
   *
90
   * <p>If your {@code executorSupplier} runs quickly and always returns a non-{@code null}
91
   * executor, then you may want to use {@link #directExecutor} to reduce latency.
92
   *
93
   * @param executorSupplier the server call executor provider
94
   * @return this
95
   * @since 1.39.0
96
   */
97
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8274")
98
  public T callExecutor(ServerCallExecutorSupplier executorSupplier) {
99
    return thisT();
×
100
  }
101

102
  /**
103
   * Adds a service implementation to the handler registry.
104
   *
105
   * @param service ServerServiceDefinition object
106
   * @return this
107
   * @since 1.0.0
108
   */
109
  public abstract T addService(ServerServiceDefinition service);
110

111
  /**
112
   * Adds a service implementation to the handler registry.
113
   *
114
   * @param bindableService BindableService object
115
   * @return this
116
   * @since 1.0.0
117
   */
118
  public abstract T addService(BindableService bindableService);
119

120
  /**
121
   * Adds a list of service implementations to the handler registry together. This exists for
122
   * convenience - equivalent to repeatedly calling addService() with different services.
123
   * If multiple services on the list use the same name, only the last one on the list will
124
   * be added.
125
   *
126
   * @param services the list of ServerServiceDefinition objects
127
   * @return this
128
   * @since 1.37.0
129
   */
130
  public final T addServices(List<ServerServiceDefinition> services) {
131
    checkNotNull(services, "services");
1✔
132
    for (ServerServiceDefinition service : services) {
1✔
133
      addService(service);
1✔
134
    }
1✔
135
    return thisT();
1✔
136
  }
137

138
  /**
139
   * Adds a {@link ServerInterceptor} that is run for all services on the server.  Interceptors
140
   * added through this method always run before per-service interceptors added through {@link
141
   * ServerInterceptors}.  Interceptors run in the reverse order in which they are added, just as
142
   * with consecutive calls to {@code ServerInterceptors.intercept()}.
143
   *
144
   * @param interceptor the all-service interceptor
145
   * @return this
146
   * @since 1.5.0
147
   */
148
  public T intercept(ServerInterceptor interceptor) {
149
    throw new UnsupportedOperationException();
×
150
  }
151

152
  /**
153
   * Adds a {@link ServerTransportFilter}. The order of filters being added is the order they will
154
   * be executed.
155
   *
156
   * @return this
157
   * @since 1.2.0
158
   */
159
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2132")
160
  public T addTransportFilter(ServerTransportFilter filter) {
161
    throw new UnsupportedOperationException();
×
162
  }
163

164
  /**
165
   * Adds a {@link ServerStreamTracer.Factory} to measure server-side traffic.  The order of
166
   * factories being added is the order they will be executed.
167
   *
168
   * @return this
169
   * @since 1.3.0
170
   */
171
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2861")
172
  public T addStreamTracerFactory(ServerStreamTracer.Factory factory) {
173
    throw new UnsupportedOperationException();
×
174
  }
175

176
  /**
177
   * Sets a fallback handler registry that will be looked up in if a method is not found in the
178
   * primary registry. The primary registry (configured via {@code addService()}) is faster but
179
   * immutable. The fallback registry is more flexible and allows implementations to mutate over
180
   * time and load services on-demand.
181
   *
182
   * @return this
183
   * @since 1.0.0
184
   */
185
  public abstract T fallbackHandlerRegistry(@Nullable HandlerRegistry fallbackRegistry);
186

187
  /**
188
   * Makes the server use TLS.
189
   *
190
   * @param certChain file containing the full certificate chain
191
   * @param privateKey file containing the private key
192
   *
193
   * @return this
194
   * @throws UnsupportedOperationException if the server does not support TLS.
195
   * @since 1.0.0
196
   */
197
  public abstract T useTransportSecurity(File certChain, File privateKey);
198

199
  /**
200
   * Makes the server use TLS.
201
   *
202
   * @param certChain InputStream containing the full certificate chain
203
   * @param privateKey InputStream containing the private key
204
   *
205
   * @return this
206
   * @throws UnsupportedOperationException if the server does not support TLS, or does not support
207
   *         reading these files from an InputStream.
208
   * @since 1.12.0
209
   */
210
  public T useTransportSecurity(InputStream certChain, InputStream privateKey) {
211
    throw new UnsupportedOperationException();
×
212
  }
213

214

215
  /**
216
   * Set the decompression registry for use in the channel.  This is an advanced API call and
217
   * shouldn't be used unless you are using custom message encoding.   The default supported
218
   * decompressors are in {@code DecompressorRegistry.getDefaultInstance}.
219
   *
220
   * @return this
221
   * @since 1.0.0
222
   */
223
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
224
  public abstract T decompressorRegistry(@Nullable DecompressorRegistry registry);
225

226
  /**
227
   * Set the compression registry for use in the channel.  This is an advanced API call and
228
   * shouldn't be used unless you are using custom message encoding.   The default supported
229
   * compressors are in {@code CompressorRegistry.getDefaultInstance}.
230
   *
231
   * @return this
232
   * @since 1.0.0
233
   */
234
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
235
  public abstract T compressorRegistry(@Nullable CompressorRegistry registry);
236

237
  /**
238
   * Sets the permitted time for new connections to complete negotiation handshakes before being
239
   * killed. The default value is 2 minutes.
240
   *
241
   * @return this
242
   * @throws IllegalArgumentException if timeout is negative
243
   * @throws UnsupportedOperationException if unsupported
244
   * @since 1.8.0
245
   */
246
  public T handshakeTimeout(long timeout, TimeUnit unit) {
247
    throw new UnsupportedOperationException();
×
248
  }
249

250
  /**
251
   * Sets the time without read activity before sending a keepalive ping. An unreasonably small
252
   * value might be increased, and {@code Long.MAX_VALUE} nano seconds or an unreasonably large
253
   * value will disable keepalive. The typical default is two hours when supported.
254
   *
255
   * @throws IllegalArgumentException if time is not positive
256
   * @throws UnsupportedOperationException if unsupported
257
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
258
   *     Server-side Connection Management</a>
259
   * @since 1.47.0
260
   */
261
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
262
  public T keepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
263
    throw new UnsupportedOperationException();
×
264
  }
265

266
  /**
267
   * Sets a time waiting for read activity after sending a keepalive ping. If the time expires
268
   * without any read activity on the connection, the connection is considered dead. An unreasonably
269
   * small value might be increased. Defaults to 20 seconds when supported.
270
   *
271
   * <p>This value should be at least multiple times the RTT to allow for lost packets.
272
   *
273
   * @throws IllegalArgumentException if timeout is not positive
274
   * @throws UnsupportedOperationException if unsupported
275
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
276
   *     Server-side Connection Management</a>
277
   * @since 1.47.0
278
   */
279
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
280
  public T keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) {
281
    throw new UnsupportedOperationException();
×
282
  }
283

284
  /**
285
   * Sets the maximum connection idle time, connections being idle for longer than which will be
286
   * gracefully terminated. Idleness duration is defined since the most recent time the number of
287
   * outstanding RPCs became zero or the connection establishment. An unreasonably small value might
288
   * be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
289
   * max connection idle.
290
   *
291
   * @throws IllegalArgumentException if idle is not positive
292
   * @throws UnsupportedOperationException if unsupported
293
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
294
   *     Server-side Connection Management</a>
295
   * @since 1.47.0
296
   */
297
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
298
  public T maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) {
299
    throw new UnsupportedOperationException();
×
300
  }
301

302
  /**
303
   * Sets the maximum connection age, connections lasting longer than which will be gracefully
304
   * terminated. An unreasonably small value might be increased. A random jitter of +/-10% will be
305
   * added to it. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
306
   * max connection age.
307
   *
308
   * @throws IllegalArgumentException if age is not positive
309
   * @throws UnsupportedOperationException if unsupported
310
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
311
   *     Server-side Connection Management</a>
312
   * @since 1.47.0
313
   */
314
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
315
  public T maxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {
316
    throw new UnsupportedOperationException();
×
317
  }
318

319
  /**
320
   * Sets the grace time for the graceful connection termination. Once the max connection age
321
   * is reached, RPCs have the grace time to complete. RPCs that do not complete in time will be
322
   * cancelled, allowing the connection to terminate. {@code Long.MAX_VALUE} nano seconds or an
323
   * unreasonably large value are considered infinite.
324
   *
325
   * @throws IllegalArgumentException if grace is negative
326
   * @throws UnsupportedOperationException if unsupported
327
   * @see #maxConnectionAge(long, TimeUnit)
328
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
329
   *     Server-side Connection Management</a>
330
   * @since 1.47.0
331
   */
332
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
333
  public T maxConnectionAgeGrace(long maxConnectionAgeGrace, TimeUnit timeUnit) {
334
    throw new UnsupportedOperationException();
×
335
  }
336

337
  /**
338
   * Specify the most aggressive keep-alive time clients are permitted to configure. The server will
339
   * try to detect clients exceeding this rate and when detected will forcefully close the
340
   * connection. The typical default is 5 minutes when supported.
341
   *
342
   * <p>Even though a default is defined that allows some keep-alives, clients must not use
343
   * keep-alive without approval from the service owner. Otherwise, they may experience failures in
344
   * the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a
345
   * significant amount of traffic and CPU usage, so clients and servers should be conservative in
346
   * what they use and accept.
347
   *
348
   * @throws IllegalArgumentException if time is negative
349
   * @throws UnsupportedOperationException if unsupported
350
   * @see #permitKeepAliveWithoutCalls(boolean)
351
   * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8
352
   *     Client-side Keepalive</a>
353
   * @since 1.47.0
354
   */
355
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
356
  public T permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
357
    throw new UnsupportedOperationException();
×
358
  }
359

360
  /**
361
   * Sets whether to allow clients to send keep-alive HTTP/2 PINGs even if there are no outstanding
362
   * RPCs on the connection. Defaults to {@code false} when supported.
363
   *
364
   * @throws UnsupportedOperationException if unsupported
365
   * @see #permitKeepAliveTime(long, TimeUnit)
366
   * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8
367
   *     Client-side Keepalive</a>
368
   * @since 1.47.0
369
   */
370
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
371
  public T permitKeepAliveWithoutCalls(boolean permit) {
372
    throw new UnsupportedOperationException();
×
373
  }
374

375
  /**
376
   * Sets the maximum message size allowed to be received on the server. If not called,
377
   * defaults to 4 MiB. The default provides protection to servers who haven't considered the
378
   * possibility of receiving large messages while trying to be large enough to not be hit in normal
379
   * usage.
380
   *
381
   * <p>This method is advisory, and implementations may decide to not enforce this.  Currently,
382
   * the only known transport to not enforce this is {@code InProcessServer}.
383
   *
384
   * @param bytes the maximum number of bytes a single message can be.
385
   * @return this
386
   * @throws IllegalArgumentException if bytes is negative.
387
   * @throws UnsupportedOperationException if unsupported.
388
   * @since 1.13.0
389
   */
390
  public T maxInboundMessageSize(int bytes) {
391
    // intentional noop rather than throw, this method is only advisory.
392
    Preconditions.checkArgument(bytes >= 0, "bytes must be >= 0");
×
393
    return thisT();
×
394
  }
395

396
  /**
397
   * Sets the maximum size of metadata allowed to be received. {@code Integer.MAX_VALUE} disables
398
   * the enforcement. The default is implementation-dependent, but is not generally less than 8 KiB
399
   * and may be unlimited.
400
   *
401
   * <p>This is cumulative size of the metadata. The precise calculation is
402
   * implementation-dependent, but implementations are encouraged to follow the calculation used for
403
   * <a href="http://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2">
404
   * HTTP/2's SETTINGS_MAX_HEADER_LIST_SIZE</a>. It sums the bytes from each entry's key and value,
405
   * plus 32 bytes of overhead per entry.
406
   *
407
   * @param bytes the maximum size of received metadata
408
   * @return this
409
   * @throws IllegalArgumentException if bytes is non-positive
410
   * @since 1.17.0
411
   */
412
  public T maxInboundMetadataSize(int bytes) {
413
    Preconditions.checkArgument(bytes > 0, "maxInboundMetadataSize must be > 0");
×
414
    // intentional noop rather than throw, this method is only advisory.
415
    return thisT();
×
416
  }
417

418
  /**
419
   * Sets the BinaryLog object that this server should log to. The server does not take
420
   * ownership of the object, and users are responsible for calling {@link BinaryLog#close()}.
421
   *
422
   * @param binaryLog the object to provide logging.
423
   * @return this
424
   * @since 1.13.0
425
   */
426
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4017")
427
  public T setBinaryLog(BinaryLog binaryLog) {
428
    throw new UnsupportedOperationException();
×
429
  }
430

431
  /**
432
   * Builds a server using the given parameters.
433
   *
434
   * <p>The returned service will not been started or be bound a port. You will need to start it
435
   * with {@link Server#start()}.
436
   *
437
   * @return a new Server
438
   * @since 1.0.0
439
   */
440
  public abstract Server build();
441

442
  /**
443
   * Adds a metric sink to the server.
444
   *
445
   * @param metricSink the metric sink to add.
446
   * @return this
447
   */
448
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/12693")
449
  public T addMetricSink(MetricSink metricSink) {
450
    return thisT();
×
451
  }
452

453
  /**
454
   * Returns the correctly typed version of the builder.
455
   */
456
  private T thisT() {
457
    @SuppressWarnings("unchecked")
458
    T thisT = (T) this;
1✔
459
    return thisT;
1✔
460
  }
461
}
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