Class GrowthBookClient
The client owns one feature repository per instance in local mode. In remote-eval mode, feature evaluation is fetched through the remote eval service and cached per user context.
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a client with default options.GrowthBookClient(Options opts) Creates a client with the supplied options. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener that is notified after a feature refresh succeeds or fails.<T> FeatureResult<T>evalFeature(String key, Class<T> valueTypeClass, UserContext userContext) Evaluates a feature for a user.<ValueType>
CompletableFuture<FeatureResult<ValueType>>evalFeatureAsync(String key, Class<ValueType> valueTypeClass, UserContext userContext) Async twin ofevalFeature(String, Class, UserContext): evaluates without blocking the caller on sticky bucket or remote-eval I/O.<ValueType>
Map<String,FeatureResult<ValueType>> evalFeatures(List<String> featureKeys, Class<ValueType> valueTypeClass, UserContext userContext) Evaluates a batch of features for the same user using a single sharedEvaluationContext.Completes when every pending sticky bucket save has been attempted.getBooleanFeature(FeatureKey<Boolean> featureKey, UserContext userContext) Get a boolean feature value, defaulting tofalsewhen missing or falsy.getBooleanFeature(FeatureKey<Boolean> featureKey, Boolean defaultValue, UserContext userContext) Get a boolean feature value.Returns a read-only snapshot of the current SDK state.getDoubleFeature(FeatureKey<Double> featureKey, Double defaultValue, UserContext userContext) Get a double feature value.<T> FeatureResult<T>getFeature(FeatureKey<T> featureKey, UserContext userContext) Evaluate a feature for a user using a type-safeFeatureKeyinstead of a raw string key.<T> CompletableFuture<FeatureResult<T>>getFeatureAsync(FeatureKey<T> featureKey, UserContext userContext) Async twin ofgetFeature(FeatureKey, UserContext).<T> TgetFeatureValue(FeatureKey<T> featureKey, T defaultValue, UserContext userContext) Get a feature value using a typed key, inferring the deserialization class from the key.<T> TgetFeatureValue(String featureKey, T defaultValue, Class<T> gsonDeserializableClass, UserContext userContext) Evaluates a feature and returns its value, falling back to the supplied default on missing or invalid values.<T> CompletableFuture<T>getFeatureValueAsync(FeatureKey<T> featureKey, T defaultValue, UserContext userContext) Async twin ofgetFeatureValue(FeatureKey, Object, UserContext).<ValueType>
CompletableFuture<ValueType>getFeatureValueAsync(String featureKey, ValueType defaultValue, Class<ValueType> gsonDeserializableClass, UserContext userContext) Async twin ofgetFeatureValue(String, Object, Class, UserContext): same deserialization and default-value semantics.getFloatFeature(FeatureKey<Float> featureKey, Float defaultValue, UserContext userContext) Get a float feature value.getIntegerFeature(FeatureKey<Integer> featureKey, Integer defaultValue, UserContext userContext) Get an integer feature value.getStringFeature(FeatureKey<String> featureKey, String defaultValue, UserContext userContext) Get a string feature value.booleanInitializes the feature repository or remote-eval service.Async twin ofinitialize(): loads features without blocking the caller.isOff(FeatureKey<?> featureKey, UserContext userContext) Checks whether the feature identified by the typed key evaluates to off for a user.isOff(String featureKey, UserContext userContext) Checks whether a feature evaluates to off for a user.isOffAsync(String featureKey, UserContext userContext) Async twin ofisOff(String, UserContext).isOn(FeatureKey<?> featureKey, UserContext userContext) Checks whether the feature identified by the typed key evaluates to on for a user.isOn(String featureKey, UserContext userContext) Checks whether a feature evaluates to on for a user.isOnAsync(String featureKey, UserContext userContext) Async twin ofisOn(String, UserContext).prefetchStickyBuckets(UserContext userContext) Prefetch sticky bucket assignments for a user context, so later evaluations with the same context perform no sticky bucket I/O.booleanpreloadRemoteEval(UserContext userContext) com.google.gson.JsonObjectreducePayload(UserContext userContext) Shrinks the current features payload for one user with the default options.com.google.gson.JsonObjectreducePayload(UserContext userContext, ReducePayloadOptions options) Shrinks the current features payload for one user, e.g.voidDeprecated.voidRefreshes feature definitions using the default refresh behavior.voidrefreshFeatures(RefreshMode refreshMode) Refreshes feature definitions using the provided refresh mode.voidrefreshForRemoteEval(RequestBodyForRemoteEval requestBodyForRemoteEval) Refreshes feature definitions using remote evaluation payload.voidRemoves a previously registered feature refresh listener.<T> ExperimentResult<T>run(Experiment<T> experiment, UserContext userContext) Runs an experiment for a user and notifies experiment subscribers when assignment changes.<ValueType>
CompletableFuture<ExperimentResult<ValueType>>runAsync(Experiment<ValueType> experiment, UserContext userContext) Async twin ofrun(Experiment, UserContext): evaluates the inline experiment and notifies experiment subscribers when assignment changes, without blocking on sticky bucket I/O.voidsetGlobalAttributes(String attributes) Replaces global attributes used for future evaluations.voidsetGlobalForceFeatures(Map<String, Object> forceFeatures) Replaces globally forced feature values used for future evaluations.voidsetGlobalForceVariations(Map<String, Integer> forceVariations) Replaces globally forced variations used for future experiment evaluations.voidshutdown()Stops repository background work and releases repository resources.voidsubscribe(ExperimentRunCallback callback) Registers an experiment run callback.Adds a listener and returns an idempotent handle that removes it.
-
Constructor Details
-
GrowthBookClient
public GrowthBookClient()Creates a client with default options. -
GrowthBookClient
Creates a client with the supplied options.- Parameters:
opts- client options; null falls back to default options
-
-
Method Details
-
getDiagnostics
Returns a read-only snapshot of the current SDK state.- Returns:
- diagnostics snapshot
-
initialize
public boolean initialize()Initializes the feature repository or remote-eval service.- Returns:
- true when the client is ready for evaluation
-
initializeAsync
Async twin ofinitialize(): loads features without blocking the caller. It runsinitialize()on the client's executor and holds one of its threads for the fetch. The returned future never completes exceptionally: it completes withfalseon invalid options, a failed fetch, an executor that rejects the task, or ashutdown()that comes first.- Returns:
- a future completing with whether the client is ready for evaluation
-
setGlobalAttributes
Replaces global attributes used for future evaluations.- Parameters:
attributes- JSON string containing global attributes
-
setGlobalForceFeatures
Replaces globally forced feature values used for future evaluations.- Parameters:
forceFeatures- feature key to forced value map
-
setGlobalForceVariations
Replaces globally forced variations used for future experiment evaluations.- Parameters:
forceVariations- experiment key to forced variation index map
-
refreshFeature
Deprecated.Fetches the latest feature definitions using the default refresh path. -
refreshFeatures
public void refreshFeatures()Refreshes feature definitions using the default refresh behavior. -
refreshFeatures
Refreshes feature definitions using the provided refresh mode.Blocks until the refresh completes, so an evaluation made right after this call sees the refreshed definitions. Use
GBFeaturesRepository.requestFeatureRefresh(RefreshMode)directly when a fire-and-forget refresh is wanted instead.In remote-eval mode this invalidates the remote-eval response cache. The next evaluation fetches a fresh remote response for that user context.
- Parameters:
refreshMode- refresh behavior to use
-
refreshForRemoteEval
Refreshes feature definitions using remote evaluation payload.- Parameters:
requestBodyForRemoteEval- remote evaluation request payload
-
preloadRemoteEval
-
evalFeature
public <T> FeatureResult<T> evalFeature(String key, Class<T> valueTypeClass, UserContext userContext) Evaluates a feature for a user.- Type Parameters:
T- feature value type- Parameters:
key- feature keyvalueTypeClass- expected value classuserContext- user context- Returns:
- feature evaluation result
-
evalFeatures
public <ValueType> Map<String,FeatureResult<ValueType>> evalFeatures(List<String> featureKeys, Class<ValueType> valueTypeClass, UserContext userContext) Evaluates a batch of features for the same user using a single sharedEvaluationContext. Attribute merging, global-context references and any sticky-bucket preload happen once for the whole batch instead of once per feature, so memory stays O(size(context)) rather than O(features × size(context)).- Type Parameters:
ValueType- the result value type- Parameters:
featureKeys- the feature keys to evaluatevalueTypeClass- the expected value type (typicallyObject.classfor mixed types)userContext- the user context, processed once- Returns:
- a map from feature key to its
FeatureResult
-
isOn
Checks whether a feature evaluates to on for a user.- Parameters:
featureKey- feature keyuserContext- user context- Returns:
- true when the feature is on
-
isOff
Checks whether a feature evaluates to off for a user.- Parameters:
featureKey- feature keyuserContext- user context- Returns:
- true when the feature is off
-
getFeatureValue
public <T> T getFeatureValue(String featureKey, T defaultValue, Class<T> gsonDeserializableClass, UserContext userContext) Evaluates a feature and returns its value, falling back to the supplied default on missing or invalid values.- Type Parameters:
T- feature value type- Parameters:
featureKey- feature keydefaultValue- fallback valuegsonDeserializableClass- expected value classuserContext- user context- Returns:
- evaluated feature value or default value
-
getFeature
Evaluate a feature for a user using a type-safeFeatureKeyinstead of a raw string key.As with
evalFeature(String, Class, UserContext), the returned result'sFeatureResult.getValue()is the raw evaluated value (a boxed primitive, or aMap/Listfor object and array features); it is not deserialized into the key's value type. To obtain a deserialized instance of a complex type, usegetFeatureValue(FeatureKey, Object, UserContext).- Type Parameters:
T- feature value type carried by the key- Parameters:
featureKey- typed feature key, e.g.Features.NEW_HOMEuserContext- user context- Returns:
- the feature result
-
isOn
Checks whether the feature identified by the typed key evaluates to on for a user.- Parameters:
featureKey- typed feature keyuserContext- user context- Returns:
- true when the feature is on
-
isOff
Checks whether the feature identified by the typed key evaluates to off for a user.- Parameters:
featureKey- typed feature keyuserContext- user context- Returns:
- true when the feature is off
-
getFeatureValue
Get a feature value using a typed key, inferring the deserialization class from the key.- Type Parameters:
T- feature value type carried by the key- Parameters:
featureKey- typed feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
getBooleanFeature
Get a boolean feature value, defaulting tofalsewhen missing or falsy.- Parameters:
featureKey- typed boolean feature keyuserContext- user context- Returns:
- the found value or
false
-
getBooleanFeature
public Boolean getBooleanFeature(FeatureKey<Boolean> featureKey, Boolean defaultValue, UserContext userContext) Get a boolean feature value.- Parameters:
featureKey- typed boolean feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
getStringFeature
public String getStringFeature(FeatureKey<String> featureKey, String defaultValue, UserContext userContext) Get a string feature value.- Parameters:
featureKey- typed string feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
getIntegerFeature
public Integer getIntegerFeature(FeatureKey<Integer> featureKey, Integer defaultValue, UserContext userContext) Get an integer feature value.- Parameters:
featureKey- typed integer feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
getDoubleFeature
public Double getDoubleFeature(FeatureKey<Double> featureKey, Double defaultValue, UserContext userContext) Get a double feature value.- Parameters:
featureKey- typed double feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
getFloatFeature
public Float getFloatFeature(FeatureKey<Float> featureKey, Float defaultValue, UserContext userContext) Get a float feature value.- Parameters:
featureKey- typed float feature keydefaultValue- value to return when the feature is missing or invaliduserContext- user context- Returns:
- the found value or defaultValue
-
run
Runs an experiment for a user and notifies experiment subscribers when assignment changes.- Type Parameters:
T- experiment value type- Parameters:
experiment- experiment to evaluateuserContext- user context- Returns:
- experiment evaluation result
-
evalFeatureAsync
public <ValueType> CompletableFuture<FeatureResult<ValueType>> evalFeatureAsync(String key, Class<ValueType> valueTypeClass, UserContext userContext) Async twin ofevalFeature(String, Class, UserContext): evaluates without blocking the caller on sticky bucket or remote-eval I/O. With no sticky bucket service configured and local evaluation, the returned future is already complete.These rules apply to every
...Asyncevaluation method:- Evaluation, tracking callbacks and the caller's continuations run on the client's executor or on the calling thread, not on the sticky bucket store's completion thread. The one exception: when the executor rejects the continuation, no other thread is left, so the future fails on the thread that completed the read.
- A sticky bucket read that fails or times out does not fail the future: the evaluation continues with normal bucketing and saves nothing.
- The future completes exceptionally when the executor rejects the work, when building
the evaluation fails, or when
shutdown()runs before the evaluation does: an evaluation still waiting on its store read is failed, not bucketed without it. Nothing is thrown on the calling thread: a nullFeatureKeyfails the future too. - The user context and its attributes must not be modified until the future completes.
- Only an
AsyncStickyBucketServicekeeps the wait free of threads. A blockingStickyBucketServiceholds one executor thread per store call, and remote evaluation holds one per evaluation. The continuation runs on the same executor, so while every one of its threads is waiting on a blocking store,Options.getStickyBucketTimeout()cannot release an evaluation until one is free.
- Type Parameters:
ValueType- feature value type- Parameters:
key- feature keyvalueTypeClass- expected value classuserContext- user context- Returns:
- a future completing with the feature result
-
isOnAsync
Async twin ofisOn(String, UserContext).- Parameters:
featureKey- feature keyuserContext- user context- Returns:
- a future completing with whether the feature is on
-
isOffAsync
Async twin ofisOff(String, UserContext).- Parameters:
featureKey- feature keyuserContext- user context- Returns:
- a future completing with whether the feature is off
-
getFeatureValueAsync
public <ValueType> CompletableFuture<ValueType> getFeatureValueAsync(String featureKey, ValueType defaultValue, Class<ValueType> gsonDeserializableClass, UserContext userContext) Async twin ofgetFeatureValue(String, Object, Class, UserContext): same deserialization and default-value semantics. Unlike the other async methods, the returned future never completes exceptionally: a rejecting executor or ashutdown()that comes first gives the default.- Type Parameters:
ValueType- feature value type- Parameters:
featureKey- feature keydefaultValue- value when the feature is missing or evaluation failsgsonDeserializableClass- expected value classuserContext- user context- Returns:
- a future completing with the deserialized value or the default
-
getFeatureAsync
public <T> CompletableFuture<FeatureResult<T>> getFeatureAsync(FeatureKey<T> featureKey, UserContext userContext) Async twin ofgetFeature(FeatureKey, UserContext).- Type Parameters:
T- feature value type carried by the key- Parameters:
featureKey- typed feature keyuserContext- user context- Returns:
- a future completing with the feature result; it fails with a
NullPointerExceptionwhenfeatureKeyis null
-
getFeatureValueAsync
public <T> CompletableFuture<T> getFeatureValueAsync(FeatureKey<T> featureKey, T defaultValue, UserContext userContext) Async twin ofgetFeatureValue(FeatureKey, Object, UserContext).- Type Parameters:
T- feature value type carried by the key- Parameters:
featureKey- typed feature keydefaultValue- value when the feature is missing or evaluation failsuserContext- user context- Returns:
- a future completing with the deserialized value or the default; it fails with a
NullPointerExceptionwhenfeatureKeyis null
-
runAsync
public <ValueType> CompletableFuture<ExperimentResult<ValueType>> runAsync(Experiment<ValueType> experiment, UserContext userContext) Async twin ofrun(Experiment, UserContext): evaluates the inline experiment and notifies experiment subscribers when assignment changes, without blocking on sticky bucket I/O.- Type Parameters:
ValueType- variation value type- Parameters:
experiment- inline experimentuserContext- user context- Returns:
- a future completing with the experiment result
-
reducePayload
public com.google.gson.JsonObject reducePayload(@Nullable UserContext userContext, @Nullable ReducePayloadOptions options) Shrinks the current features payload for one user, e.g. to bootstrap a client SDK during server-side rendering. The result evaluates the same as the full payload for anyone who agrees with the known attributes: this client's global attributes overlaid by the user's.The payload is the one held by this client's feature repository: its features and saved groups. The repository doesn't keep auto experiments or contextual bandits, so the result's
experimentslist is empty. To reduce a whole payload, usePayloadReducer.reducePayload(com.google.gson.JsonObject, com.google.gson.JsonObject, growthbook.sdk.java.model.ReducePayloadOptions). Safe for concurrent use.- Parameters:
userContext- the attributes known for the user;nullfor noneoptions- filters and prerequisite handling;nullfor defaults- Returns:
- a new payload JSON object with
features,experimentsandsavedGroups
-
reducePayload
Shrinks the current features payload for one user with the default options.- Parameters:
userContext- the attributes known for the user;nullfor none- Returns:
- a new payload JSON object
- See Also:
-
subscribe
Registers an experiment run callback.- Parameters:
callback- callback invoked when an experiment assignment changes
-
addFeatureRefreshListener
Adds a listener that is notified after a feature refresh succeeds or fails.Listeners never run on the thread that performed the refresh: they are dispatched on
Options.getFeatureRefreshListenerExecutor(), or on a dedicated daemon thread when none is configured. A listener may therefore block without stalling polling or SSE updates. If that executor rejects the task the event is dropped with a warning rather than run inline, so configuring a rejecting executor gives back-pressure, not blocking.- Parameters:
listener- listener to add
-
subscribeFeatureRefreshListener
Adds a listener and returns an idempotent handle that removes it.Dispatch and threading are as described on
addFeatureRefreshListener(growthbook.sdk.java.listener.FeatureRefreshListener).- Parameters:
listener- listener to add- Returns:
- subscription handle
-
removeFeatureRefreshListener
Removes a previously registered feature refresh listener.- Parameters:
listener- listener to remove
-
shutdown
public void shutdown()Stops repository background work and releases repository resources.Synchronized so concurrent shutdown calls cannot interleave teardown of the repository, the remote-eval coordinator, the listener executor, and the plugin registry.
-
prefetchStickyBuckets
Prefetch sticky bucket assignments for a user context, so later evaluations with the same context perform no sticky bucket I/O. The context'sstickyBucketAssignmentDocsis populated and the same instance is returned. The populated map is concurrency-safe, so the returned context may be reused across concurrent evaluations.The read covers the attributes the loaded features' experiments hash on, plus
Options.stickyBucketIdentifierAttributes. An inline experiment later passed torunwith this context is covered only if its hash attribute is one of those; list it instickyBucketIdentifierAttributesotherwise, or its stored assignment is not read.- Parameters:
userContext- the request-scoped user context to prefetch for- Returns:
- a future completing with the same context, docs populated
-
flushStickyBucketSaves
Completes when every pending sticky bucket save has been attempted. This is not a durability guarantee: a save the store rejects is logged and kept for the next write or flush, so a completed flush future means "no save is still outstanding", not "every assignment reached the store". Fire-and-forget writes do not need this; short-lived processes should await it (or callshutdown(), which flushes automatically) before exiting to drain in-flight saves.- Returns:
- a future completing when all pending saves have been attempted
-
refreshFeatures()orrefreshFeatures(RefreshMode).