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

grpc / grpc-java / #20220

25 Mar 2026 06:04AM UTC coverage: 88.693%. Remained the same
#20220

push

github

web-flow
api: Deprecate LoadBalancer.handleResolvedAddresses() (#11623)

Also deprecate its companion
canHandleEmptyAddressListFromNameResolution().
Also fixup the Javadoc to align with the arguments/return values, so
that people would have a better idea of how to use it.

Fixes #11194

---------

Co-authored-by: MV Shiva Prasad <okshiva@google.com>
Co-authored-by: Eric Anderson <ejona@google.com>

35486 of 40010 relevant lines covered (88.69%)

0.89 hits per line

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

79.65
/../api/src/main/java/io/grpc/LoadBalancer.java
1
/*
2
 * Copyright 2016 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.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21

22
import com.google.common.base.MoreObjects;
23
import com.google.common.base.Objects;
24
import com.google.common.base.Preconditions;
25
import java.util.ArrayList;
26
import java.util.Arrays;
27
import java.util.Collections;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.concurrent.ScheduledExecutorService;
31
import javax.annotation.Nonnull;
32
import javax.annotation.Nullable;
33
import javax.annotation.concurrent.Immutable;
34
import javax.annotation.concurrent.NotThreadSafe;
35
import javax.annotation.concurrent.ThreadSafe;
36

37
/**
38
 * A pluggable component that receives resolved addresses from {@link NameResolver} and provides the
39
 * channel a usable subchannel when asked.
40
 *
41
 * <h3>Overview</h3>
42
 *
43
 * <p>A LoadBalancer typically implements three interfaces:
44
 * <ol>
45
 *   <li>{@link LoadBalancer} is the main interface.  All methods on it are invoked sequentially
46
 *       in the same <strong>synchronization context</strong> (see next section) as returned by
47
 *       {@link io.grpc.LoadBalancer.Helper#getSynchronizationContext}.  It receives the results
48
 *       from the {@link NameResolver}, updates of subchannels' connectivity states, and the
49
 *       channel's request for the LoadBalancer to shutdown.</li>
50
 *   <li>{@link SubchannelPicker SubchannelPicker} does the actual load-balancing work.  It selects
51
 *       a {@link Subchannel Subchannel} for each new RPC.</li>
52
 *   <li>{@link Factory Factory} creates a new {@link LoadBalancer} instance.
53
 * </ol>
54
 *
55
 * <p>{@link Helper Helper} is implemented by gRPC library and provided to {@link Factory
56
 * Factory}. It provides functionalities that a {@code LoadBalancer} implementation would typically
57
 * need.
58
 *
59
 * <h3>The Synchronization Context</h3>
60
 *
61
 * <p>All methods on the {@link LoadBalancer} interface are called from a Synchronization Context,
62
 * meaning they are serialized, thus the balancer implementation doesn't need to worry about
63
 * synchronization among them.  {@link io.grpc.LoadBalancer.Helper#getSynchronizationContext}
64
 * allows implementations to schedule tasks to be run in the same Synchronization Context, with or
65
 * without a delay, thus those tasks don't need to worry about synchronizing with the balancer
66
 * methods.
67
 * 
68
 * <p>However, the actual running thread may be the network thread, thus the following rules must be
69
 * followed to prevent blocking or even dead-locking in a network:
70
 *
71
 * <ol>
72
 *
73
 *   <li><strong>Never block in the Synchronization Context</strong>.  The callback methods must
74
 *   return quickly.  Examples or work that must be avoided: CPU-intensive calculation, waiting on
75
 *   synchronization primitives, blocking I/O, blocking RPCs, etc.</li>
76
 *
77
 *   <li><strong>Avoid calling into other components with lock held</strong>.  The Synchronization
78
 *   Context may be under a lock, e.g., the transport lock of OkHttp.  If your LoadBalancer holds a
79
 *   lock in a callback method (e.g., {@link #handleResolvedAddresses handleResolvedAddresses()})
80
 *   while calling into another method that also involves locks, be cautious of deadlock.  Generally
81
 *   you wouldn't need any locking in the LoadBalancer if you follow the canonical implementation
82
 *   pattern below.</li>
83
 *
84
 * </ol>
85
 *
86
 * <h3>The canonical implementation pattern</h3>
87
 *
88
 * <p>A {@link LoadBalancer} keeps states like the latest addresses from NameResolver, the
89
 * Subchannel(s) and their latest connectivity states.  These states are mutated within the
90
 * Synchronization Context,
91
 *
92
 * <p>A typical {@link SubchannelPicker SubchannelPicker} holds a snapshot of these states.  It may
93
 * have its own states, e.g., a picker from a round-robin load-balancer may keep a pointer to the
94
 * next Subchannel, which are typically mutated by multiple threads.  The picker should only mutate
95
 * its own state, and should not mutate or re-acquire the states of the LoadBalancer.  This way the
96
 * picker only needs to synchronize its own states, which is typically trivial to implement.
97
 *
98
 * <p>When the LoadBalancer states changes, e.g., Subchannels has become or stopped being READY, and
99
 * we want subsequent RPCs to use the latest list of READY Subchannels, LoadBalancer would create a
100
 * new picker, which holds a snapshot of the latest Subchannel list.  Refer to the javadoc of {@link
101
 * io.grpc.LoadBalancer.SubchannelStateListener#onSubchannelState onSubchannelState()} how to do
102
 * this properly.
103
 *
104
 * <p>No synchronization should be necessary between LoadBalancer and its pickers if you follow
105
 * the pattern above.  It may be possible to implement in a different way, but that would usually
106
 * result in more complicated threading.
107
 *
108
 * @since 1.2.0
109
 */
110
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
111
@NotThreadSafe
112
public abstract class LoadBalancer {
1✔
113

114
  @Internal
115
  @NameResolver.ResolutionResultAttr
116
  public static final Attributes.Key<Map<String, ?>> ATTR_HEALTH_CHECKING_CONFIG =
1✔
117
      Attributes.Key.create("internal:health-checking-config");
1✔
118

119
  @Internal
120
  public static final LoadBalancer.CreateSubchannelArgs.Key<LoadBalancer.SubchannelStateListener>
121
      HEALTH_CONSUMER_LISTENER_ARG_KEY =
1✔
122
      LoadBalancer.CreateSubchannelArgs.Key.create("internal:health-check-consumer-listener");
1✔
123

124
  @Internal
125
  public static final LoadBalancer.CreateSubchannelArgs.Key<Boolean>
126
      DISABLE_SUBCHANNEL_RECONNECT_KEY =
1✔
127
      LoadBalancer.CreateSubchannelArgs.Key.createWithDefault(
1✔
128
          "internal:disable-subchannel-reconnect", Boolean.FALSE);
129

130
  @Internal
131
  public static final Attributes.Key<Boolean>
132
      HAS_HEALTH_PRODUCER_LISTENER_KEY =
1✔
133
      Attributes.Key.create("internal:has-health-check-producer-listener");
1✔
134

135
  public static final Attributes.Key<Boolean> IS_PETIOLE_POLICY =
1✔
136
      Attributes.Key.create("io.grpc.IS_PETIOLE_POLICY");
1✔
137

138
  /**
139
   * A picker that always returns an erring pick.
140
   *
141
   * @deprecated Use {@code new FixedResultPicker(PickResult.withNoResult())} instead.
142
   */
143
  @Deprecated
144
  public static final SubchannelPicker EMPTY_PICKER = new SubchannelPicker() {
1✔
145
    @Override
146
    public PickResult pickSubchannel(PickSubchannelArgs args) {
147
      return PickResult.withNoResult();
×
148
    }
149

150
    @Override
151
    public String toString() {
152
      return "EMPTY_PICKER";
×
153
    }
154
  };
155

156
  private int recursionCount;
157

158
  /**
159
   * Handles newly resolved addresses and metadata attributes from name resolution system.
160
   * Addresses in {@link EquivalentAddressGroup} should be considered equivalent but may be
161
   * flattened into a single list if needed.
162
   *
163
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
164
   * @since 1.21.0
165
   *
166
   * @deprecated  Use instead {@link #acceptResolvedAddresses(ResolvedAddresses)}
167
   */
168
  @Deprecated
169
  public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
170
    if (recursionCount++ == 0) {
1✔
171
      // Note that the information about the addresses actually being accepted will be lost
172
      // if you rely on this method for backward compatibility.
173
      acceptResolvedAddresses(resolvedAddresses);
1✔
174
    }
175
    recursionCount = 0;
1✔
176
  }
1✔
177

178
  /**
179
   * Accepts newly resolved addresses from the name resolution system. The {@link
180
   * EquivalentAddressGroup} addresses should be considered equivalent but may be flattened into a
181
   * single list if needed.
182
   *
183
   * @param resolvedAddresses the resolved server addresses, attributes, and config
184
   * @return {@code Status.OK} if the resolved addresses were accepted, otherwise an error to report
185
   *     to the name resolver
186
   *
187
   * @since 1.49.0
188
   */
189
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
190
    if (resolvedAddresses.getAddresses().isEmpty()
1✔
191
        && !canHandleEmptyAddressListFromNameResolution()) {
×
192
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
×
193
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
×
194
                      + ", attrs=" + resolvedAddresses.getAttributes());
×
195
      handleNameResolutionError(unavailableStatus);
×
196
      return unavailableStatus;
×
197
    } else {
198
      if (recursionCount++ == 0) {
1✔
199
        handleResolvedAddresses(resolvedAddresses);
×
200
      }
201
      recursionCount = 0;
1✔
202

203
      return Status.OK;
1✔
204
    }
205
  }
206

207
  /**
208
   * Represents a combination of the resolved server address, associated attributes and a load
209
   * balancing policy config.  The config is from the {@link
210
   * LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
211
   *
212
   * @since 1.21.0
213
   */
214
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11657")
215
  public static final class ResolvedAddresses {
216
    private final List<EquivalentAddressGroup> addresses;
217
    @NameResolver.ResolutionResultAttr
218
    private final Attributes attributes;
219
    @Nullable
220
    private final Object loadBalancingPolicyConfig;
221
    // Make sure to update toBuilder() below!
222

223
    private ResolvedAddresses(
224
        List<EquivalentAddressGroup> addresses,
225
        @NameResolver.ResolutionResultAttr Attributes attributes,
226
        Object loadBalancingPolicyConfig) {
1✔
227
      this.addresses =
1✔
228
          Collections.unmodifiableList(new ArrayList<>(checkNotNull(addresses, "addresses")));
1✔
229
      this.attributes = checkNotNull(attributes, "attributes");
1✔
230
      this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
231
    }
1✔
232

233
    /**
234
     * Factory for constructing a new Builder.
235
     *
236
     * @since 1.21.0
237
     */
238
    public static Builder newBuilder() {
239
      return new Builder();
1✔
240
    }
241

242
    /**
243
     * Converts this back to a builder.
244
     *
245
     * @since 1.21.0
246
     */
247
    public Builder toBuilder() {
248
      return newBuilder()
1✔
249
          .setAddresses(addresses)
1✔
250
          .setAttributes(attributes)
1✔
251
          .setLoadBalancingPolicyConfig(loadBalancingPolicyConfig);
1✔
252
    }
253

254
    /**
255
     * Gets the server addresses.
256
     *
257
     * @since 1.21.0
258
     */
259
    public List<EquivalentAddressGroup> getAddresses() {
260
      return addresses;
1✔
261
    }
262

263
    /**
264
     * Gets the attributes associated with these addresses.  If this was not previously set,
265
     * {@link Attributes#EMPTY} will be returned.
266
     *
267
     * @since 1.21.0
268
     */
269
    @NameResolver.ResolutionResultAttr
270
    public Attributes getAttributes() {
271
      return attributes;
1✔
272
    }
273

274
    /**
275
     * Gets the domain specific load balancing policy.  This is the config produced by
276
     * {@link LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
277
     *
278
     * @since 1.21.0
279
     */
280
    @Nullable
281
    public Object getLoadBalancingPolicyConfig() {
282
      return loadBalancingPolicyConfig;
1✔
283
    }
284

285
    /**
286
     * Builder for {@link ResolvedAddresses}.
287
     */
288
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
289
    public static final class Builder {
290
      private List<EquivalentAddressGroup> addresses;
291
      @NameResolver.ResolutionResultAttr
1✔
292
      private Attributes attributes = Attributes.EMPTY;
293
      @Nullable
294
      private Object loadBalancingPolicyConfig;
295

296
      Builder() {}
1✔
297

298
      /**
299
       * Sets the addresses.  This field is required.
300
       *
301
       * @return this.
302
       */
303
      public Builder setAddresses(List<EquivalentAddressGroup> addresses) {
304
        this.addresses = addresses;
1✔
305
        return this;
1✔
306
      }
307

308
      /**
309
       * Sets the attributes.  This field is optional; if not called, {@link Attributes#EMPTY}
310
       * will be used.
311
       *
312
       * @return this.
313
       */
314
      public Builder setAttributes(@NameResolver.ResolutionResultAttr Attributes attributes) {
315
        this.attributes = attributes;
1✔
316
        return this;
1✔
317
      }
318

319
      /**
320
       * Sets the load balancing policy config. This field is optional.
321
       *
322
       * @return this.
323
       */
324
      public Builder setLoadBalancingPolicyConfig(@Nullable Object loadBalancingPolicyConfig) {
325
        this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
326
        return this;
1✔
327
      }
328

329
      /**
330
       * Constructs the {@link ResolvedAddresses}.
331
       */
332
      public ResolvedAddresses build() {
333
        return new ResolvedAddresses(addresses, attributes, loadBalancingPolicyConfig);
1✔
334
      }
335
    }
336

337
    @Override
338
    public String toString() {
339
      return MoreObjects.toStringHelper(this)
1✔
340
          .add("addresses", addresses)
1✔
341
          .add("attributes", attributes)
1✔
342
          .add("loadBalancingPolicyConfig", loadBalancingPolicyConfig)
1✔
343
          .toString();
1✔
344
    }
345

346
    @Override
347
    public int hashCode() {
348
      return Objects.hashCode(addresses, attributes, loadBalancingPolicyConfig);
×
349
    }
350

351
    @Override
352
    public boolean equals(Object obj) {
353
      if (!(obj instanceof ResolvedAddresses)) {
1✔
354
        return false;
×
355
      }
356
      ResolvedAddresses that = (ResolvedAddresses) obj;
1✔
357
      return Objects.equal(this.addresses, that.addresses)
1✔
358
          && Objects.equal(this.attributes, that.attributes)
1✔
359
          && Objects.equal(this.loadBalancingPolicyConfig, that.loadBalancingPolicyConfig);
1✔
360
    }
361
  }
362

363
  /**
364
   * Handles an error from the name resolution system.
365
   *
366
   * @param error a non-OK status
367
   * @since 1.2.0
368
   */
369
  public abstract void handleNameResolutionError(Status error);
370

371
  /**
372
   * Handles a state change on a Subchannel.
373
   *
374
   * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial IDLE
375
   * state.
376
   *
377
   * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
378
   * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
379
   * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
380
   * PickResult.withSubchannel()}'s javadoc for more information.
381
   *
382
   * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
383
   * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The other
384
   * is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has already
385
   * terminated, thus there won't be further requests to LoadBalancer.  Therefore, the LoadBalancer
386
   * usually don't need to react to a SHUTDOWN state.
387
   *
388
   * @param subchannel the involved Subchannel
389
   * @param stateInfo the new state
390
   * @since 1.2.0
391
   * @deprecated This method will be removed.  Stop overriding it.  Instead, pass {@link
392
   *             SubchannelStateListener} to {@link Subchannel#start} to receive Subchannel state
393
   *             updates
394
   */
395
  @Deprecated
396
  public void handleSubchannelState(
397
      Subchannel subchannel, ConnectivityStateInfo stateInfo) {
398
    // Do nothing.  If the implementation doesn't implement this, it will get subchannel states from
399
    // the new API.  We don't throw because there may be forwarding LoadBalancers still plumb this.
400
  }
×
401

402
  /**
403
   * The channel asks the load-balancer to shutdown.  No more methods on this class will be called
404
   * after this method.  The implementation should shutdown all Subchannels and OOB channels, and do
405
   * any other cleanup as necessary.
406
   *
407
   * @since 1.2.0
408
   */
409
  public abstract void shutdown();
410

411
  /**
412
   * Whether this LoadBalancer can handle empty address group list to be passed to {@link
413
   * #handleResolvedAddresses(ResolvedAddresses)}.  The default implementation returns
414
   * {@code false}, meaning that if the NameResolver returns an empty list, the Channel will turn
415
   * that into an error and call {@link #handleNameResolutionError}.  LoadBalancers that want to
416
   * accept empty lists should override this method and return {@code true}.
417
   *
418
   * <p>This method should always return a constant value.  It's not specified when this will be
419
   * called.
420
   * 
421
   * <p>Note that this method is only called when implementing {@code handleResolvedAddresses()}
422
   * instead of {@code acceptResolvedAddresses()}.
423
   *
424
   * @deprecated Instead of overwriting this and {@code handleResolvedAddresses()}, only
425
   *     overwrite {@code acceptResolvedAddresses()} which indicates if the addresses provided
426
   *     by the name resolver are acceptable with the {@code boolean} return value.
427
   */
428
  @Deprecated
429
  @SuppressWarnings("InlineMeSuggester")
430
  public boolean canHandleEmptyAddressListFromNameResolution() {
431
    return false;
×
432
  }
433

434
  /**
435
   * The channel asks the LoadBalancer to establish connections now (if applicable) so that the
436
   * upcoming RPC may then just pick a ready connection without waiting for connections.  This
437
   * is triggered by {@link ManagedChannel#getState ManagedChannel.getState(true)}.
438
   *
439
   * <p>If LoadBalancer doesn't override it, this is no-op.  If it infeasible to create connections
440
   * given the current state, e.g. no Subchannel has been created yet, LoadBalancer can ignore this
441
   * request.
442
   *
443
   * @since 1.22.0
444
   */
445
  public void requestConnection() {}
1✔
446

447
  /**
448
   * The main balancing logic.  It <strong>must be thread-safe</strong>. Typically it should only
449
   * synchronize on its own state, and avoid synchronizing with the LoadBalancer's state.
450
   *
451
   * @since 1.2.0
452
   */
453
  @ThreadSafe
454
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
455
  public abstract static class SubchannelPicker {
1✔
456
    /**
457
     * Make a balancing decision for a new RPC.
458
     *
459
     * @param args the pick arguments
460
     * @since 1.3.0
461
     */
462
    public abstract PickResult pickSubchannel(PickSubchannelArgs args);
463
  }
464

465
  /**
466
   * Provides arguments for a {@link SubchannelPicker#pickSubchannel(
467
   * LoadBalancer.PickSubchannelArgs)}.
468
   *
469
   * @since 1.2.0
470
   */
471
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
472
  public abstract static class PickSubchannelArgs {
1✔
473

474
    /**
475
     * Call options.
476
     *
477
     * @since 1.2.0
478
     */
479
    public abstract CallOptions getCallOptions();
480

481
    /**
482
     * Headers of the call. {@link SubchannelPicker#pickSubchannel} may mutate it before before
483
     * returning.
484
     *
485
     * @since 1.2.0
486
     */
487
    public abstract Metadata getHeaders();
488

489
    /**
490
     * Call method.
491
     *
492
     * @since 1.2.0
493
     */
494
    public abstract MethodDescriptor<?, ?> getMethodDescriptor();
495

496
    /**
497
     * Gets an object that can be informed about what sort of pick was made.
498
     */
499
    @Internal
500
    public PickDetailsConsumer getPickDetailsConsumer() {
501
      return new PickDetailsConsumer() {};
×
502
    }
503
  }
504

505
  /** Receives information about the pick being chosen. */
506
  @Internal
507
  public interface PickDetailsConsumer {
508
    /**
509
     * Optional labels that provide context of how the pick was routed. Particularly helpful for
510
     * per-RPC metrics.
511
     *
512
     * @throws NullPointerException if key or value is {@code null}
513
     */
514
    default void addOptionalLabel(String key, String value) {
515
      checkNotNull(key, "key");
1✔
516
      checkNotNull(value, "value");
1✔
517
    }
1✔
518
  }
519

520
  /**
521
   * A balancing decision made by {@link SubchannelPicker SubchannelPicker} for an RPC.
522
   *
523
   * <p>The outcome of the decision will be one of the following:
524
   * <ul>
525
   *   <li>Proceed: if a Subchannel is provided via {@link #withSubchannel withSubchannel()}, and is
526
   *       in READY state when the RPC tries to start on it, the RPC will proceed on that
527
   *       Subchannel.</li>
528
   *   <li>Error: if an error is provided via {@link #withError withError()}, and the RPC is not
529
   *       wait-for-ready (i.e., {@link CallOptions#withWaitForReady} was not called), the RPC will
530
   *       fail immediately with the given error.</li>
531
   *   <li>Buffer: in all other cases, the RPC will be buffered in the Channel, until the next
532
   *       picker is provided via {@link Helper#updateBalancingState Helper.updateBalancingState()},
533
   *       when the RPC will go through the same picking process again.</li>
534
   * </ul>
535
   *
536
   * @since 1.2.0
537
   */
538
  @Immutable
539
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
540
  public static final class PickResult {
541
    private static final PickResult NO_RESULT = new PickResult(null, null, Status.OK, false);
1✔
542

543
    @Nullable private final Subchannel subchannel;
544
    @Nullable private final ClientStreamTracer.Factory streamTracerFactory;
545
    // An error to be propagated to the application if subchannel == null
546
    // Or OK if there is no error.
547
    // subchannel being null and error being OK means RPC needs to wait
548
    private final Status status;
549
    // True if the result is created by withDrop()
550
    private final boolean drop;
551
    @Nullable private final String authorityOverride;
552

553
    private PickResult(
554
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
555
        Status status, boolean drop) {
1✔
556
      this.subchannel = subchannel;
1✔
557
      this.streamTracerFactory = streamTracerFactory;
1✔
558
      this.status = checkNotNull(status, "status");
1✔
559
      this.drop = drop;
1✔
560
      this.authorityOverride = null;
1✔
561
    }
1✔
562

563
    private PickResult(
564
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
565
        Status status, boolean drop, @Nullable String authorityOverride) {
1✔
566
      this.subchannel = subchannel;
1✔
567
      this.streamTracerFactory = streamTracerFactory;
1✔
568
      this.status = checkNotNull(status, "status");
1✔
569
      this.drop = drop;
1✔
570
      this.authorityOverride = authorityOverride;
1✔
571
    }
1✔
572

573
    /**
574
     * A decision to proceed the RPC on a Subchannel.
575
     *
576
     * <p>The Subchannel should either be an original Subchannel returned by {@link
577
     * Helper#createSubchannel Helper.createSubchannel()}, or a wrapper of it preferably based on
578
     * {@code ForwardingSubchannel}.  At the very least its {@link Subchannel#getInternalSubchannel
579
     * getInternalSubchannel()} must return the same object as the one returned by the original.
580
     * Otherwise the Channel cannot use it for the RPC.
581
     *
582
     * <p>When the RPC tries to use the return Subchannel, which is briefly after this method
583
     * returns, the state of the Subchannel will decide where the RPC would go:
584
     *
585
     * <ul>
586
     *   <li>READY: the RPC will proceed on this Subchannel.</li>
587
     *   <li>IDLE: the RPC will be buffered.  Subchannel will attempt to create connection.</li>
588
     *   <li>All other states: the RPC will be buffered.</li>
589
     * </ul>
590
     *
591
     * <p><strong>All buffered RPCs will stay buffered</strong> until the next call of {@link
592
     * Helper#updateBalancingState Helper.updateBalancingState()}, which will trigger a new picking
593
     * process.
594
     *
595
     * <p>Note that Subchannel's state may change at the same time the picker is making the
596
     * decision, which means the decision may be made with (to-be) outdated information.  For
597
     * example, a picker may return a Subchannel known to be READY, but it has become IDLE when is
598
     * about to be used by the RPC, which makes the RPC to be buffered.  The LoadBalancer will soon
599
     * learn about the Subchannels' transition from READY to IDLE, create a new picker and allow the
600
     * RPC to use another READY transport if there is any.
601
     *
602
     * <p>You will want to avoid running into a situation where there are READY Subchannels out
603
     * there but some RPCs are still buffered for longer than a brief time.
604
     * <ul>
605
     *   <li>This can happen if you return Subchannels with states other than READY and IDLE.  For
606
     *       example, suppose you round-robin on 2 Subchannels, in READY and CONNECTING states
607
     *       respectively.  If the picker ignores the state and pick them equally, 50% of RPCs will
608
     *       be stuck in buffered state until both Subchannels are READY.</li>
609
     *   <li>This can also happen if you don't create a new picker at key state changes of
610
     *       Subchannels.  Take the above round-robin example again.  Suppose you do pick only READY
611
     *       and IDLE Subchannels, and initially both Subchannels are READY.  Now one becomes IDLE,
612
     *       then CONNECTING and stays CONNECTING for a long time.  If you don't create a new picker
613
     *       in response to the CONNECTING state to exclude that Subchannel, 50% of RPCs will hit it
614
     *       and be buffered even though the other Subchannel is READY.</li>
615
     * </ul>
616
     *
617
     * <p>In order to prevent unnecessary delay of RPCs, the rules of thumb are:
618
     * <ol>
619
     *   <li>The picker should only pick Subchannels that are known as READY or IDLE.  Whether to
620
     *       pick IDLE Subchannels depends on whether you want Subchannels to connect on-demand or
621
     *       actively:
622
     *       <ul>
623
     *         <li>If you want connect-on-demand, include IDLE Subchannels in your pick results,
624
     *             because when an RPC tries to use an IDLE Subchannel, the Subchannel will try to
625
     *             connect.</li>
626
     *         <li>If you want Subchannels to be always connected even when there is no RPC, you
627
     *             would call {@link Subchannel#requestConnection Subchannel.requestConnection()}
628
     *             whenever the Subchannel has transitioned to IDLE, then you don't need to include
629
     *             IDLE Subchannels in your pick results.</li>
630
     *       </ul></li>
631
     *   <li>Always create a new picker and call {@link Helper#updateBalancingState
632
     *       Helper.updateBalancingState()} whenever {@link #handleSubchannelState
633
     *       handleSubchannelState()} is called, unless the new state is SHUTDOWN. See
634
     *       {@code handleSubchannelState}'s javadoc for more details.</li>
635
     * </ol>
636
     *
637
     * @param subchannel the picked Subchannel.  It must have been {@link Subchannel#start started}
638
     * @param streamTracerFactory if not null, will be used to trace the activities of the stream
639
     *                            created as a result of this pick. Note it's possible that no
640
     *                            stream is created at all in some cases.
641
     * @since 1.3.0
642
     */
643
    // TODO(shivaspeaks): Need to deprecate old APIs and create new ones, 
644
    // per https://github.com/grpc/grpc-java/issues/12662.
645
    public static PickResult withSubchannel(
646
        Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory) {
647
      return new PickResult(
1✔
648
          checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
1✔
649
          false);
650
    }
651

652
    /**
653
     * Same as {@code withSubchannel(subchannel, streamTracerFactory)} but with an authority name
654
     * to override in the host header.
655
     */
656
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
657
    public static PickResult withSubchannel(
658
        Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
659
        @Nullable String authorityOverride) {
660
      return new PickResult(
1✔
661
          checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
1✔
662
          false, authorityOverride);
663
    }
664

665
    /**
666
     * Equivalent to {@code withSubchannel(subchannel, null)}.
667
     *
668
     * @since 1.2.0
669
     */
670
    public static PickResult withSubchannel(Subchannel subchannel) {
671
      return withSubchannel(subchannel, null);
1✔
672
    }
673

674
    /**
675
     * Creates a new {@code PickResult} with the given {@code subchannel},
676
     * but retains all other properties from this {@code PickResult}.
677
     *
678
     * @since 1.80.0
679
     */
680
    public PickResult copyWithSubchannel(Subchannel subchannel) {
681
      return new PickResult(checkNotNull(subchannel, "subchannel"), streamTracerFactory,
1✔
682
          status, drop, authorityOverride);
683
    }
684

685
    /**
686
     * Creates a new {@code PickResult} with the given {@code streamTracerFactory},
687
     * but retains all other properties from this {@code PickResult}.
688
     *
689
     * @since 1.80.0
690
     */
691
    public PickResult copyWithStreamTracerFactory(
692
        @Nullable ClientStreamTracer.Factory streamTracerFactory) {
693
      return new PickResult(subchannel, streamTracerFactory, status, drop, authorityOverride);
1✔
694
    }
695

696
    /**
697
     * A decision to report a connectivity error to the RPC.  If the RPC is {@link
698
     * CallOptions#withWaitForReady wait-for-ready}, it will stay buffered.  Otherwise, it will fail
699
     * with the given error.
700
     *
701
     * @param error the error status.  Must not be OK.
702
     * @since 1.2.0
703
     */
704
    public static PickResult withError(Status error) {
705
      Preconditions.checkArgument(!error.isOk(), "error status shouldn't be OK");
1✔
706
      return new PickResult(null, null, error, false);
1✔
707
    }
708

709
    /**
710
     * A decision to fail an RPC immediately.  This is a final decision and will ignore retry
711
     * policy.
712
     *
713
     * @param status the status with which the RPC will fail.  Must not be OK.
714
     * @since 1.8.0
715
     */
716
    public static PickResult withDrop(Status status) {
717
      Preconditions.checkArgument(!status.isOk(), "drop status shouldn't be OK");
1✔
718
      return new PickResult(null, null, status, true);
1✔
719
    }
720

721
    /**
722
     * No decision could be made.  The RPC will stay buffered.
723
     *
724
     * @since 1.2.0
725
     */
726
    public static PickResult withNoResult() {
727
      return NO_RESULT;
1✔
728
    }
729

730
    /** Returns the authority override if any. */
731
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
732
    @Nullable
733
    public String getAuthorityOverride() {
734
      return authorityOverride;
1✔
735
    }
736

737
    /**
738
     * The Subchannel if this result was created by {@link #withSubchannel withSubchannel()}, or
739
     * null otherwise.
740
     *
741
     * @since 1.2.0
742
     */
743
    @Nullable
744
    public Subchannel getSubchannel() {
745
      return subchannel;
1✔
746
    }
747

748
    /**
749
     * The stream tracer factory this result was created with.
750
     *
751
     * @since 1.3.0
752
     */
753
    @Nullable
754
    public ClientStreamTracer.Factory getStreamTracerFactory() {
755
      return streamTracerFactory;
1✔
756
    }
757

758
    /**
759
     * The status associated with this result.  Non-{@code OK} if created with {@link #withError
760
     * withError}, or {@code OK} otherwise.
761
     *
762
     * @since 1.2.0
763
     */
764
    public Status getStatus() {
765
      return status;
1✔
766
    }
767

768
    /**
769
     * Returns {@code true} if this result was created by {@link #withDrop withDrop()}.
770
     *
771
     * @since 1.8.0
772
     */
773
    public boolean isDrop() {
774
      return drop;
1✔
775
    }
776

777
    /**
778
     * Returns {@code true} if the pick was not created with {@link #withNoResult()}.
779
     */
780
    public boolean hasResult() {
781
      return !(subchannel == null && status.isOk());
1✔
782
    }
783

784
    @Override
785
    public String toString() {
786
      return MoreObjects.toStringHelper(this)
1✔
787
          .add("subchannel", subchannel)
1✔
788
          .add("streamTracerFactory", streamTracerFactory)
1✔
789
          .add("status", status)
1✔
790
          .add("drop", drop)
1✔
791
          .add("authority-override", authorityOverride)
1✔
792
          .toString();
1✔
793
    }
794

795
    @Override
796
    public int hashCode() {
797
      return Objects.hashCode(subchannel, status, streamTracerFactory, drop);
1✔
798
    }
799

800
    /**
801
     * Returns true if the {@link Subchannel}, {@link Status}, and
802
     * {@link ClientStreamTracer.Factory} all match.
803
     */
804
    @Override
805
    public boolean equals(Object other) {
806
      if (!(other instanceof PickResult)) {
1✔
807
        return false;
×
808
      }
809
      PickResult that = (PickResult) other;
1✔
810
      return Objects.equal(subchannel, that.subchannel) && Objects.equal(status, that.status)
1✔
811
          && Objects.equal(streamTracerFactory, that.streamTracerFactory)
1✔
812
          && drop == that.drop;
813
    }
814
  }
815

816
  /**
817
   * Arguments for creating a {@link Subchannel}.
818
   *
819
   * @since 1.22.0
820
   */
821
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
822
  public static final class CreateSubchannelArgs {
823
    private final List<EquivalentAddressGroup> addrs;
824
    private final Attributes attrs;
825
    private final Object[][] customOptions;
826

827
    private CreateSubchannelArgs(
828
        List<EquivalentAddressGroup> addrs, Attributes attrs, Object[][] customOptions) {
1✔
829
      this.addrs = checkNotNull(addrs, "addresses are not set");
1✔
830
      this.attrs = checkNotNull(attrs, "attrs");
1✔
831
      this.customOptions = checkNotNull(customOptions, "customOptions");
1✔
832
    }
1✔
833

834
    /**
835
     * Returns the addresses, which is an unmodifiable list.
836
     */
837
    public List<EquivalentAddressGroup> getAddresses() {
838
      return addrs;
1✔
839
    }
840

841
    /**
842
     * Returns the attributes.
843
     */
844
    public Attributes getAttributes() {
845
      return attrs;
1✔
846
    }
847

848
    /**
849
     * Get the value for a custom option or its inherent default.
850
     *
851
     * @param key Key identifying option
852
     */
853
    @SuppressWarnings("unchecked")
854
    public <T> T getOption(Key<T> key) {
855
      Preconditions.checkNotNull(key, "key");
1✔
856
      for (int i = 0; i < customOptions.length; i++) {
1✔
857
        if (key.equals(customOptions[i][0])) {
1✔
858
          return (T) customOptions[i][1];
1✔
859
        }
860
      }
861
      return key.defaultValue;
1✔
862
    }
863

864
    /**
865
     * Returns a builder with the same initial values as this object.
866
     */
867
    public Builder toBuilder() {
868
      return newBuilder().setAddresses(addrs).setAttributes(attrs).copyCustomOptions(customOptions);
1✔
869
    }
870

871
    /**
872
     * Creates a new builder.
873
     */
874
    public static Builder newBuilder() {
875
      return new Builder();
1✔
876
    }
877

878
    @Override
879
    public String toString() {
880
      return MoreObjects.toStringHelper(this)
1✔
881
          .add("addrs", addrs)
1✔
882
          .add("attrs", attrs)
1✔
883
          .add("customOptions", Arrays.deepToString(customOptions))
1✔
884
          .toString();
1✔
885
    }
886

887
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
888
    public static final class Builder {
889

890
      private static final Object[][] EMPTY_CUSTOM_OPTIONS = new Object[0][2];
1✔
891

892
      private List<EquivalentAddressGroup> addrs;
893
      private Attributes attrs = Attributes.EMPTY;
1✔
894
      private Object[][] customOptions = EMPTY_CUSTOM_OPTIONS;
1✔
895

896
      Builder() {
1✔
897
      }
1✔
898

899
      private Builder copyCustomOptions(Object[][] options) {
900
        customOptions = new Object[options.length][2];
1✔
901
        System.arraycopy(options, 0, customOptions, 0, options.length);
1✔
902
        return this;
1✔
903
      }
904

905
      /**
906
       * Add a custom option. Any existing value for the key is overwritten.
907
       *
908
       * <p>This is an <strong>optional</strong> property.
909
       *
910
       * @param key the option key
911
       * @param value the option value
912
       */
913
      public <T> Builder addOption(Key<T> key, T value) {
914
        Preconditions.checkNotNull(key, "key");
1✔
915
        Preconditions.checkNotNull(value, "value");
1✔
916

917
        int existingIdx = -1;
1✔
918
        for (int i = 0; i < customOptions.length; i++) {
1✔
919
          if (key.equals(customOptions[i][0])) {
1✔
920
            existingIdx = i;
1✔
921
            break;
1✔
922
          }
923
        }
924

925
        if (existingIdx == -1) {
1✔
926
          Object[][] newCustomOptions = new Object[customOptions.length + 1][2];
1✔
927
          System.arraycopy(customOptions, 0, newCustomOptions, 0, customOptions.length);
1✔
928
          customOptions = newCustomOptions;
1✔
929
          existingIdx = customOptions.length - 1;
1✔
930
        }
931
        customOptions[existingIdx] = new Object[]{key, value};
1✔
932
        return this;
1✔
933
      }
934

935
      /**
936
       * The addresses to connect to.  All addresses are considered equivalent and will be tried
937
       * in the order they are provided.
938
       */
939
      public Builder setAddresses(EquivalentAddressGroup addrs) {
940
        this.addrs = Collections.singletonList(addrs);
1✔
941
        return this;
1✔
942
      }
943

944
      /**
945
       * The addresses to connect to.  All addresses are considered equivalent and will
946
       * be tried in the order they are provided.
947
       *
948
       * <p>This is a <strong>required</strong> property.
949
       *
950
       * @throws IllegalArgumentException if {@code addrs} is empty
951
       */
952
      public Builder setAddresses(List<EquivalentAddressGroup> addrs) {
953
        checkArgument(!addrs.isEmpty(), "addrs is empty");
1✔
954
        this.addrs = Collections.unmodifiableList(new ArrayList<>(addrs));
1✔
955
        return this;
1✔
956
      }
957

958
      /**
959
       * Attributes provided here will be included in {@link Subchannel#getAttributes}.
960
       *
961
       * <p>This is an <strong>optional</strong> property.  Default is empty if not set.
962
       */
963
      public Builder setAttributes(Attributes attrs) {
964
        this.attrs = checkNotNull(attrs, "attrs");
1✔
965
        return this;
1✔
966
      }
967

968
      /**
969
       * Creates a new args object.
970
       */
971
      public CreateSubchannelArgs build() {
972
        return new CreateSubchannelArgs(addrs, attrs, customOptions);
1✔
973
      }
974
    }
975

976
    /**
977
     * Key for a key-value pair. Uses reference equality.
978
     */
979
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
980
    public static final class Key<T> {
981

982
      private final String debugString;
983
      private final T defaultValue;
984

985
      private Key(String debugString, T defaultValue) {
1✔
986
        this.debugString = debugString;
1✔
987
        this.defaultValue = defaultValue;
1✔
988
      }
1✔
989

990
      /**
991
       * Factory method for creating instances of {@link Key}. The default value of the key is
992
       * {@code null}.
993
       *
994
       * @param debugString a debug string that describes this key.
995
       * @param <T> Key type
996
       * @return Key object
997
       */
998
      public static <T> Key<T> create(String debugString) {
999
        Preconditions.checkNotNull(debugString, "debugString");
1✔
1000
        return new Key<>(debugString, /*defaultValue=*/ null);
1✔
1001
      }
1002

1003
      /**
1004
       * Factory method for creating instances of {@link Key}.
1005
       *
1006
       * @param debugString a debug string that describes this key.
1007
       * @param defaultValue default value to return when value for key not set
1008
       * @param <T> Key type
1009
       * @return Key object
1010
       */
1011
      public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
1012
        Preconditions.checkNotNull(debugString, "debugString");
1✔
1013
        return new Key<>(debugString, defaultValue);
1✔
1014
      }
1015

1016
      /**
1017
       * Returns the user supplied default value for this key.
1018
       */
1019
      public T getDefault() {
1020
        return defaultValue;
×
1021
      }
1022

1023
      @Override
1024
      public String toString() {
1025
        return debugString;
1✔
1026
      }
1027
    }
1028
  }
1029

1030
  /**
1031
   * Provides essentials for LoadBalancer implementations.
1032
   *
1033
   * @since 1.2.0
1034
   */
1035
  @ThreadSafe
1036
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1037
  public abstract static class Helper {
1✔
1038
    /**
1039
     * Creates a Subchannel, which is a logical connection to the given group of addresses which are
1040
     * considered equivalent.  The {@code attrs} are custom attributes associated with this
1041
     * Subchannel, and can be accessed later through {@link Subchannel#getAttributes
1042
     * Subchannel.getAttributes()}.
1043
     *
1044
     * <p>The LoadBalancer is responsible for closing unused Subchannels, and closing all
1045
     * Subchannels within {@link #shutdown}.
1046
     *
1047
     * <p>It must be called from {@link #getSynchronizationContext the Synchronization Context}
1048
     *
1049
     * @return Must return a valid Subchannel object, may not return null.
1050
     *
1051
     * @since 1.22.0
1052
     */
1053
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
1054
      throw new UnsupportedOperationException();
1✔
1055
    }
1056

1057
    /**
1058
     * Create an out-of-band channel for the LoadBalancer’s own RPC needs, e.g., talking to an
1059
     * external load-balancer service.
1060
     *
1061
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1062
     * channels within {@link #shutdown}.
1063
     *
1064
     * @since 1.4.0
1065
     */
1066
    public abstract ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority);
1067

1068
    /**
1069
     * Create an out-of-band channel for the LoadBalancer's own RPC needs, e.g., talking to an
1070
     * external load-balancer service. This version of the method allows multiple EAGs, so different
1071
     * addresses can have different authorities.
1072
     *
1073
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1074
     * channels within {@link #shutdown}.
1075
     * */
1076
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> eag,
1077
        String authority) {
1078
      throw new UnsupportedOperationException();
×
1079
    }
1080

1081
    /**
1082
     * Updates the addresses used for connections in the {@code Channel} that was created by {@link
1083
     * #createOobChannel(EquivalentAddressGroup, String)}. This is superior to {@link
1084
     * #createOobChannel(EquivalentAddressGroup, String)} when the old and new addresses overlap,
1085
     * since the channel can continue using an existing connection.
1086
     *
1087
     * @throws IllegalArgumentException if {@code channel} was not returned from {@link
1088
     *     #createOobChannel}
1089
     * @since 1.4.0
1090
     */
1091
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1092
      throw new UnsupportedOperationException();
×
1093
    }
1094

1095
    /**
1096
     * Updates the addresses with a new EAG list. Connection is continued when old and new addresses
1097
     * overlap.
1098
     * */
1099
    public void updateOobChannelAddresses(ManagedChannel channel,
1100
        List<EquivalentAddressGroup> eag) {
1101
      throw new UnsupportedOperationException();
×
1102
    }
1103

1104
    /**
1105
     * Creates an out-of-band channel for LoadBalancer's own RPC needs, e.g., talking to an external
1106
     * load-balancer service, that is specified by a target string.  See the documentation on
1107
     * {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1108
     *
1109
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1110
     * target string.
1111
     *
1112
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1113
     * channels within {@link #shutdown}.
1114
     *
1115
     * @since 1.20.0
1116
     */
1117
    public ManagedChannel createResolvingOobChannel(String target) {
1118
      return createResolvingOobChannelBuilder(target).build();
1✔
1119
    }
1120

1121
    /**
1122
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1123
     * external load-balancer service, that is specified by a target string.  See the documentation
1124
     * on {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1125
     *
1126
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1127
     * target string.
1128
     *
1129
     * <p>The returned oob-channel builder defaults to use the same authority and ChannelCredentials
1130
     * (without bearer tokens) as the parent channel's for authentication. This is different from
1131
     * {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}.
1132
     *
1133
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1134
     * channels within {@link #shutdown}.
1135
     *
1136
     * @deprecated Use {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}
1137
     *     instead.
1138
     * @since 1.31.0
1139
     */
1140
    @Deprecated
1141
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1142
      throw new UnsupportedOperationException("Not implemented");
×
1143
    }
1144

1145
    /**
1146
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1147
     * external load-balancer service, that is specified by a target string and credentials.  See
1148
     * the documentation on {@link Grpc#newChannelBuilder} for the format of a target string.
1149
     *
1150
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1151
     * target string.
1152
     *
1153
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1154
     * channels within {@link #shutdown}.
1155
     *
1156
     * @since 1.35.0
1157
     */
1158
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1159
        String target, ChannelCredentials creds) {
1160
      throw new UnsupportedOperationException();
×
1161
    }
1162

1163
    /**
1164
     * Set a new state with a new picker to the channel.
1165
     *
1166
     * <p>When a new picker is provided via {@code updateBalancingState()}, the channel will apply
1167
     * the picker on all buffered RPCs, by calling {@link SubchannelPicker#pickSubchannel(
1168
     * LoadBalancer.PickSubchannelArgs)}.
1169
     *
1170
     * <p>The channel will hold the picker and use it for all RPCs, until {@code
1171
     * updateBalancingState()} is called again and a new picker replaces the old one.  If {@code
1172
     * updateBalancingState()} has never been called, the channel will buffer all RPCs until a
1173
     * picker is provided.
1174
     *
1175
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1176
     * violated.  It will become an exception eventually.  See <a
1177
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1178
     *
1179
     * <p>The passed state will be the channel's new state. The SHUTDOWN state should not be passed
1180
     * and its behavior is undefined.
1181
     *
1182
     * @since 1.6.0
1183
     */
1184
    public abstract void updateBalancingState(
1185
        @Nonnull ConnectivityState newState, @Nonnull SubchannelPicker newPicker);
1186

1187
    /**
1188
     * Call {@link NameResolver#refresh} on the channel's resolver.
1189
     *
1190
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1191
     * violated.  It will become an exception eventually.  See <a
1192
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1193
     *
1194
     * @since 1.18.0
1195
     */
1196
    public void refreshNameResolution() {
1197
      throw new UnsupportedOperationException();
×
1198
    }
1199

1200
    /**
1201
     * Historically the channel automatically refreshes name resolution if any subchannel
1202
     * connection is broken. It's transitioning to let load balancers make the decision. To
1203
     * avoid silent breakages, the channel checks if {@link #refreshNameResolution} is called
1204
     * by the load balancer. If not, it will do it and log a warning. This will be removed in
1205
     * the future and load balancers are completely responsible for triggering the refresh.
1206
     * See <a href="https://github.com/grpc/grpc-java/issues/8088">#8088</a> for the background.
1207
     *
1208
     * <p>This should rarely be used, but sometimes the address for the subchannel wasn't
1209
     * provided by the name resolver and a refresh needs to be directed somewhere else instead.
1210
     * Then you can call this method to disable the short-tem check for detecting LoadBalancers
1211
     * that need to be updated for the new expected behavior.
1212
     *
1213
     * @since 1.38.0
1214
     * @deprecated Warning has been removed
1215
     */
1216
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8088")
1217
    @Deprecated
1218
    public void ignoreRefreshNameResolutionCheck() {
1219
      // no-op
1220
    }
×
1221

1222
    /**
1223
     * Returns a {@link SynchronizationContext} that runs tasks in the same Synchronization Context
1224
     * as that the callback methods on the {@link LoadBalancer} interface are run in.
1225
     *
1226
     * <p>Work added to the synchronization context might not run immediately, so LB implementations
1227
     * must be careful to ensure that any assumptions still hold when it is executed. In particular,
1228
     * the LB might have been shut down or subchannels might have changed state.
1229
     *
1230
     * <p>Pro-tip: in order to call {@link SynchronizationContext#schedule}, you need to provide a
1231
     * {@link ScheduledExecutorService}.  {@link #getScheduledExecutorService} is provided for your
1232
     * convenience.
1233
     *
1234
     * @since 1.17.0
1235
     */
1236
    public SynchronizationContext getSynchronizationContext() {
1237
      // TODO(zhangkun): make getSynchronizationContext() abstract after runSerialized() is deleted
1238
      throw new UnsupportedOperationException();
×
1239
    }
1240

1241
    /**
1242
     * Returns a {@link ScheduledExecutorService} for scheduling delayed tasks.
1243
     *
1244
     * <p>This service is a shared resource and is only meant for quick tasks.  DO NOT block or run
1245
     * time-consuming tasks.
1246
     *
1247
     * <p>The returned service doesn't support {@link ScheduledExecutorService#shutdown shutdown()}
1248
     * and {@link ScheduledExecutorService#shutdownNow shutdownNow()}.  They will throw if called.
1249
     *
1250
     * @since 1.17.0
1251
     */
1252
    public ScheduledExecutorService getScheduledExecutorService() {
1253
      throw new UnsupportedOperationException();
×
1254
    }
1255

1256
    /**
1257
     * Returns the authority string of the channel, which is derived from the DNS-style target name.
1258
     * If overridden by a load balancer, {@link #getUnsafeChannelCredentials} must also be
1259
     * overridden to call {@link #getChannelCredentials} or provide appropriate credentials.
1260
     *
1261
     * @since 1.2.0
1262
     */
1263
    public abstract String getAuthority();
1264

1265
    /**
1266
     * Returns the target string of the channel, guaranteed to include its scheme.
1267
     */
1268
    public String getChannelTarget() {
1269
      throw new UnsupportedOperationException();
×
1270
    }
1271

1272
    /**
1273
     * Returns the ChannelCredentials used to construct the channel, without bearer tokens.
1274
     *
1275
     * @since 1.35.0
1276
     */
1277
    public ChannelCredentials getChannelCredentials() {
1278
      return getUnsafeChannelCredentials().withoutBearerTokens();
×
1279
    }
1280

1281
    /**
1282
     * Returns the UNSAFE ChannelCredentials used to construct the channel,
1283
     * including bearer tokens. Load balancers should generally have no use for
1284
     * these credentials and use of them is heavily discouraged. These must be used
1285
     * <em>very</em> carefully to avoid sending bearer tokens to untrusted servers
1286
     * as the server could then impersonate the client. Generally it is only safe
1287
     * to use these credentials when communicating with the backend.
1288
     *
1289
     * @since 1.35.0
1290
     */
1291
    public ChannelCredentials getUnsafeChannelCredentials() {
1292
      throw new UnsupportedOperationException();
×
1293
    }
1294

1295
    /**
1296
     * Returns the {@link ChannelLogger} for the Channel served by this LoadBalancer.
1297
     *
1298
     * @since 1.17.0
1299
     */
1300
    public ChannelLogger getChannelLogger() {
1301
      throw new UnsupportedOperationException();
×
1302
    }
1303

1304
    /**
1305
     * Returns the {@link NameResolver.Args} that the Channel uses to create {@link NameResolver}s.
1306
     *
1307
     * @since 1.22.0
1308
     */
1309
    public NameResolver.Args getNameResolverArgs() {
1310
      throw new UnsupportedOperationException();
×
1311
    }
1312

1313
    /**
1314
     * Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link
1315
     * NameResolver}s.
1316
     *
1317
     * @since 1.22.0
1318
     */
1319
    public NameResolverRegistry getNameResolverRegistry() {
1320
      throw new UnsupportedOperationException();
×
1321
    }
1322

1323
    /**
1324
     * Returns the {@link MetricRecorder} that the channel uses to record metrics.
1325
     *
1326
     * @since 1.64.0
1327
     */
1328
    @Internal
1329
    public MetricRecorder getMetricRecorder() {
1330
      return new MetricRecorder() {};
×
1331
    }
1332
  }
1333

1334
  /**
1335
   * A logical connection to a server, or a group of equivalent servers represented by an {@link 
1336
   * EquivalentAddressGroup}.
1337
   *
1338
   * <p>It maintains at most one physical connection (aka transport) for sending new RPCs, while
1339
   * also keeps track of previous transports that has been shut down but not terminated yet.
1340
   *
1341
   * <p>If there isn't an active transport yet, and an RPC is assigned to the Subchannel, it will
1342
   * create a new transport.  It won't actively create transports otherwise.  {@link
1343
   * #requestConnection requestConnection()} can be used to ask Subchannel to create a transport if
1344
   * there isn't any.
1345
   *
1346
   * <p>{@link #start} must be called prior to calling any other methods, with the exception of
1347
   * {@link #shutdown}, which can be called at any time.
1348
   *
1349
   * @since 1.2.0
1350
   */
1351
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1352
  public abstract static class Subchannel {
1✔
1353
    /**
1354
     * Starts the Subchannel.  Can only be called once.
1355
     *
1356
     * <p>Must be called prior to any other method on this class, except for {@link #shutdown} which
1357
     * may be called at any time.
1358
     *
1359
     * <p>Must be called from the {@link Helper#getSynchronizationContext Synchronization Context},
1360
     * otherwise it may throw.  See <a href="https://github.com/grpc/grpc-java/issues/5015">
1361
     * #5015</a> for more discussions.
1362
     *
1363
     * @param listener receives state updates for this Subchannel.
1364
     */
1365
    public void start(SubchannelStateListener listener) {
1366
      throw new UnsupportedOperationException("Not implemented");
×
1367
    }
1368

1369
    /**
1370
     * Shuts down the Subchannel.  After this method is called, this Subchannel should no longer
1371
     * be returned by the latest {@link SubchannelPicker picker}, and can be safely discarded.
1372
     *
1373
     * <p>Calling it on an already shut-down Subchannel has no effect.
1374
     *
1375
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1376
     * violated.  It will become an exception eventually.  See <a
1377
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1378
     *
1379
     * @since 1.2.0
1380
     */
1381
    public abstract void shutdown();
1382

1383
    /**
1384
     * Asks the Subchannel to create a connection (aka transport), if there isn't an active one.
1385
     *
1386
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1387
     * violated.  It will become an exception eventually.  See <a
1388
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1389
     *
1390
     * @since 1.2.0
1391
     */
1392
    public abstract void requestConnection();
1393

1394
    /**
1395
     * Returns the addresses that this Subchannel is bound to.  This can be called only if
1396
     * the Subchannel has only one {@link EquivalentAddressGroup}.  Under the hood it calls
1397
     * {@link #getAllAddresses}.
1398
     *
1399
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1400
     * violated.  It will become an exception eventually.  See <a
1401
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1402
     *
1403
     * @throws IllegalStateException if this subchannel has more than one EquivalentAddressGroup.
1404
     *         Use {@link #getAllAddresses} instead
1405
     * @since 1.2.0
1406
     */
1407
    public final EquivalentAddressGroup getAddresses() {
1408
      List<EquivalentAddressGroup> groups = getAllAddresses();
1✔
1409
      Preconditions.checkState(groups != null && groups.size() == 1,
1✔
1410
          "%s does not have exactly one group", groups);
1411
      return groups.get(0);
1✔
1412
    }
1413

1414
    /**
1415
     * Returns the addresses that this Subchannel is bound to. The returned list will not be empty.
1416
     *
1417
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1418
     * violated.  It will become an exception eventually.  See <a
1419
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1420
     *
1421
     * @since 1.14.0
1422
     */
1423
    public List<EquivalentAddressGroup> getAllAddresses() {
1424
      throw new UnsupportedOperationException();
×
1425
    }
1426

1427
    /**
1428
     * The same attributes passed to {@link Helper#createSubchannel Helper.createSubchannel()}.
1429
     * LoadBalancer can use it to attach additional information here, e.g., the shard this
1430
     * Subchannel belongs to.
1431
     *
1432
     * @since 1.2.0
1433
     */
1434
    public abstract Attributes getAttributes();
1435

1436
    /**
1437
     * (Internal use only) returns a {@link Channel} that is backed by this Subchannel.  This allows
1438
     * a LoadBalancer to issue its own RPCs for auxiliary purposes, such as health-checking, on
1439
     * already-established connections.  This channel has certain restrictions:
1440
     * <ol>
1441
     *   <li>It can issue RPCs only if the Subchannel is {@code READY}. If {@link
1442
     *   Channel#newCall} is called when the Subchannel is not {@code READY}, the RPC will fail
1443
     *   immediately.</li>
1444
     *   <li>It doesn't support {@link CallOptions#withWaitForReady wait-for-ready} RPCs. Such RPCs
1445
     *   will fail immediately.</li>
1446
     * </ol>
1447
     *
1448
     * <p>RPCs made on this Channel is not counted when determining ManagedChannel's {@link
1449
     * ManagedChannelBuilder#idleTimeout idle mode}.  In other words, they won't prevent
1450
     * ManagedChannel from entering idle mode.
1451
     *
1452
     * <p>Warning: RPCs made on this channel will prevent a shut-down transport from terminating. If
1453
     * you make long-running RPCs, you need to make sure they will finish in time after the
1454
     * Subchannel has transitioned away from {@code READY} state
1455
     * (notified through {@link #handleSubchannelState}).
1456
     *
1457
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1458
     * change without notice. If you think you must use it, please file an issue.
1459
     */
1460
    @Internal
1461
    public Channel asChannel() {
1462
      throw new UnsupportedOperationException();
×
1463
    }
1464

1465
    /**
1466
     * Returns a {@link ChannelLogger} for this Subchannel.
1467
     *
1468
     * @since 1.17.0
1469
     */
1470
    public ChannelLogger getChannelLogger() {
1471
      throw new UnsupportedOperationException();
×
1472
    }
1473

1474
    /**
1475
     * Replaces the existing addresses used with this {@code Subchannel}. If the new and old
1476
     * addresses overlap, the Subchannel can continue using an existing connection.
1477
     *
1478
     * <p>It must be called from the Synchronization Context or will throw.
1479
     *
1480
     * @throws IllegalArgumentException if {@code addrs} is empty
1481
     * @since 1.22.0
1482
     */
1483
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
1484
      throw new UnsupportedOperationException();
×
1485
    }
1486

1487
    /**
1488
     * (Internal use only) returns an object that represents the underlying subchannel that is used
1489
     * by the Channel for sending RPCs when this {@link Subchannel} is picked.  This is an opaque
1490
     * object that is both provided and consumed by the Channel.  Its type <strong>is not</strong>
1491
     * {@code Subchannel}.
1492
     *
1493
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1494
     * change without notice. If you think you must use it, please file an issue and we can consider
1495
     * removing its "internal" status.
1496
     */
1497
    @Internal
1498
    public Object getInternalSubchannel() {
1499
      throw new UnsupportedOperationException();
×
1500
    }
1501

1502
    /**
1503
     * (Internal use only) returns attributes of the address subchannel is connected to.
1504
     *
1505
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1506
     * change without notice. If you think you must use it, please file an issue and we can consider
1507
     * removing its "internal" status.
1508
     */
1509
    @Internal
1510
    public Attributes getConnectedAddressAttributes() {
1511
      throw new UnsupportedOperationException();
×
1512
    }
1513
  }
1514

1515
  /**
1516
   * Receives state changes for one {@link Subchannel}. All methods are run under {@link
1517
   * Helper#getSynchronizationContext}.
1518
   *
1519
   * @since 1.22.0
1520
   */
1521
  public interface SubchannelStateListener {
1522
    /**
1523
     * Handles a state change on a Subchannel.
1524
     *
1525
     * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial
1526
     * IDLE state.
1527
     *
1528
     * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
1529
     * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
1530
     * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
1531
     * PickResult.withSubchannel()}'s javadoc for more information.
1532
     *
1533
     * <p>When a subchannel's state is IDLE or TRANSIENT_FAILURE and the address for the subchannel
1534
     * was received in {@link LoadBalancer#handleResolvedAddresses}, load balancers should call
1535
     * {@link Helper#refreshNameResolution} to inform polling name resolvers that it is an
1536
     * appropriate time to refresh the addresses. Without the refresh, changes to the addresses may
1537
     * never be detected.
1538
     *
1539
     * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
1540
     * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The
1541
     * other is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has
1542
     * already terminated, thus there won't be further requests to LoadBalancer.  Therefore, the
1543
     * LoadBalancer usually don't need to react to a SHUTDOWN state.
1544
     *
1545
     * @param newState the new state
1546
     * @since 1.22.0
1547
     */
1548
    void onSubchannelState(ConnectivityStateInfo newState);
1549
  }
1550

1551
  /**
1552
   * Factory to create {@link LoadBalancer} instance.
1553
   *
1554
   * @since 1.2.0
1555
   */
1556
  @ThreadSafe
1557
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1558
  public abstract static class Factory {
1✔
1559
    /**
1560
     * Creates a {@link LoadBalancer} that will be used inside a channel.
1561
     *
1562
     * @since 1.2.0
1563
     */
1564
    public abstract LoadBalancer newLoadBalancer(Helper helper);
1565
  }
1566

1567
  /**
1568
   * A picker that always returns an erring pick.
1569
   *
1570
   * @deprecated Use {@code new FixedResultPicker(PickResult.withError(error))} instead.
1571
   */
1572
  @Deprecated
1573
  public static final class ErrorPicker extends SubchannelPicker {
1574

1575
    private final Status error;
1576

1577
    public ErrorPicker(Status error) {
×
1578
      this.error = checkNotNull(error, "error");
×
1579
    }
×
1580

1581
    @Override
1582
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1583
      return PickResult.withError(error);
×
1584
    }
1585

1586
    @Override
1587
    public String toString() {
1588
      return MoreObjects.toStringHelper(this)
×
1589
          .add("error", error)
×
1590
          .toString();
×
1591
    }
1592
  }
1593

1594
  /** A picker that always returns the same result. */
1595
  public static final class FixedResultPicker extends SubchannelPicker {
1596
    private final PickResult result;
1597

1598
    public FixedResultPicker(PickResult result) {
1✔
1599
      this.result = Preconditions.checkNotNull(result, "result");
1✔
1600
    }
1✔
1601

1602
    @Override
1603
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1604
      return result;
1✔
1605
    }
1606

1607
    @Override
1608
    public String toString() {
1609
      return "FixedResultPicker(" + result + ")";
1✔
1610
    }
1611

1612
    @Override
1613
    public int hashCode() {
1614
      return result.hashCode();
1✔
1615
    }
1616

1617
    @Override
1618
    public boolean equals(Object o) {
1619
      if (!(o instanceof FixedResultPicker)) {
1✔
1620
        return false;
1✔
1621
      }
1622
      FixedResultPicker that = (FixedResultPicker) o;
1✔
1623
      return this.result.equals(that.result);
1✔
1624
    }
1625
  }
1626
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc