Java
Latest Version: v1.0.0
Updated: 2026-10-27
1. Overview
Starting from version 6.1, AE supports the Experiment Suite, which allows you to create experiments in the AE console, configure variable values for control and experiment groups, and retrieve experiment information through the SDK to show different content to users in different groups.
This document describes how to integrate the Java server-side SDK. You only need to focus on interaction with the ThinkingData SDK, without needing to handle task details in the AE console.
The Java server-side Experiment SDK retrieves Feature configurations from AE experiments. Your service passes the current user identifiers and the required Feature Keys. The configuration center (RCC) performs remote allocation, and the SDK returns the configuration values and information about the matched experiments. Your service executes its logic based on the configuration and uploads an exposure event after the configuration is actually used.
- A Feature Key identifies a variable configured in the AE console. The examples use checkout_button; replace it with the actual Key for your project during integration.
- The client does not automatically fetch the current user's experiment configuration after initialization. Your service initiates requests through fetch(FeatureRequest) or fetch(accountId, distinctId).
- A Feature's default configuration value may still be returned when no experiment is matched.
2. SDK Integration
2.1 Environment and Dependencies
JDK 8 or later is required. The SDK is published on Maven Central. We recommend adding it through Maven or Gradle so that the required transitive dependencies are resolved automatically.
<dependency>
<groupId>cn.thinkingdata</groupId>
<artifactId>td-feature-java</artifactId>
<version>1.0.0</version>
</dependency>
Gradle example:
repositories {
mavenCentral()
}
dependencies {
implementation 'cn.thinkingdata:td-feature-java:1.0.0'
}
The groupId in the Maven coordinates is cn.thinkingdata; the Java package name remains cn.thinkingai.feature. The runtime dependencies declared in the POM are as follows:
| Dependency | Purpose | Version Declared in the 1.0.0 POM |
|---|---|---|
| thinkingdatasdk | Java data collection SDK, used to upload exposure events | 3.0.6 |
| httpclient | Accesses the configuration center | 4.5.14 |
| caffeine | Configuration caching and exposure deduplication | 2.9.3 |
| slf4j-api | Logging API; your application provides the logging implementation | 1.7.36 |
| guava / re2j / commons-codec | Base dependencies | 31.1-jre / 1.8 / 1.14 |
These dependencies are included transitively with the SDK, so you usually do not need to add them individually.
3. Initialization and Quick Start
3.1 Complete Example:
The following example uses the default SDK configuration. The SDK automatically creates a data collection instance, retrieves all Features visible to the current user, obtains all Keys through getFeatureKeys(), and then selects checkout_button for use in your service and manually uploads an exposure event. Reuse TDFeatureClient as a singleton within your application for each App ID and service URL; construct a separate FeatureRequest for the current user with each request. Set serverUrl to a service root URL that supports both configuration queries and data collection, and replace the App ID, user identifiers, and business Key with actual values.
import cn.thinkingai.feature.api.FeatureConfig;
import cn.thinkingai.feature.api.FeatureRequest;
import cn.thinkingai.feature.api.FeatureResult;
import cn.thinkingai.feature.api.SplitMode;
import cn.thinkingai.feature.api.TDFeatureClient;
import cn.thinkingai.feature.common.Config;
import java.util.Collections;
import java.util.Set;
public class RemoteSplitQuickStart {
public static void main(String[] args) throws Exception {
String appId = "YOUR_APP_ID";
TDFeatureClient client = new TDFeatureClient(Config.builder()
.appId(appId)
.serverUrl("https://YOUR_SERVER_URL")
.splitMode(SplitMode.REMOTE)
.build());
try {
String buttonStyle = "control"; // Business default value
FeatureResult feature = null;
try {
FeatureConfig config = client.fetch(FeatureRequest.builder()
.accountId("user_123")
.distinctId("visitor_456")
// Omit featureKey/featureKeys to fetch all configurations visible to the current user
.build());
Set<String> featureKeys = config.getFeatureKeys();
System.out.println("All Feature Keys returned in this request: " + featureKeys);
feature = config.getFeature("checkout_button");
if (feature != null && feature.hasValue()) {
buttonStyle = feature.getValueAsString("control");
}
} catch (RuntimeException e) {
// Use the business default value and log the error if the request fails
System.err.println("Configuration request failed: " + e.getMessage());
}
} finally {
// In a real service, run this only when the application exits; do not close the singleton after each request
client.close();
}
}
}
3.2 Existing TDAnalytics Instance
If your application already uses the Java data collection SDK (TDAnalytics), keep its existing initialization, Consumer, and reporting configuration. After the data collection SDK is initialized, pass the same TDAnalytics singleton held by your application to tdAnalytics(...), then create the Experiment SDK. You do not need to create another data collection instance.
import cn.thinkingai.feature.api.SplitMode;
import cn.thinkingai.feature.api.TDFeatureClient;
import cn.thinkingai.feature.common.Config;
import cn.thinkingdata.analytics.TDAnalytics;
public class ExistingAnalyticsIntegration {
public static TDFeatureClient createFeatureClient(
String appId, String rccServerUrl, TDAnalytics analytics) {
if (analytics == null) {
throw new IllegalArgumentException("Pass the existing TDAnalytics instance used by your application");
}
return new TDFeatureClient(Config.builder()
.appId(appId)
.serverUrl(rccServerUrl)
.splitMode(SplitMode.REMOTE)
.tdAnalytics(analytics) // Reuse the existing data collection SDK
.build());
}
}
4. Retrieve Configuration and Experiment Information
4.1 Pass the Current User Identity
| Request Parameter | Meaning | Usage Requirements |
|---|---|---|
| accountId | Account ID, corresponding to #account_id | For experiments allocated by account, pass an accurate, stable account ID. |
| distinctId | Visitor ID, corresponding to #distinct_id | For experiments allocated by visitor, pass a visitor ID that matches the definition in the AE console. |
Pass at least one non-empty value for accountId or distinctId; you can pass both. Providing an ID alone does not guarantee that an experiment will be matched. The identity you pass must satisfy the allocation subject and audience conditions configured in the AE console. When the user changes, pass the new user's identifiers in a new request; do not reuse FeatureResult across users.
4.2 Retrieve One or More Features
FeatureConfig config = client.fetch(FeatureRequest.builder()
.accountId("user_123")
.featureKeys("checkout_button", "recommendation_enabled", "discount_rate", "page_config")
.build());
FeatureResult button = config.getFeature("checkout_button");
String buttonStyle = button == null
? "control" : button.getValueAsString("control");
Use featureKey("checkout_button") for a single Key and featureKeys(...) for multiple Keys, with support for varargs and List<String>. Request Keys according to your business needs to reduce transfer and result-processing overhead. getFeature(key) returns null when the returned result does not contain that Key.
4.3 Read Configuration Values of Different Types
| Variable Type in the AE Console | Read Method | Return Type |
|---|---|---|
| String | getValueAsString(defaultValue) | String |
| Number | getValueAsDouble(defaultValue) | Double |
| Boolean | getValueAsBoolean(defaultValue) | Boolean |
| JSON | getValueAsJson(defaultValue) | com.alibaba.fastjson2.JSONObject |
| Raw value | getValue() | Object |
FeatureConfig config = client.fetch(FeatureRequest.builder()
.accountId("user_123")
.featureKeys("recommendation_enabled", "discount_rate", "page_config")
.build());
FeatureResult enabledFeature = config.getFeature("recommendation_enabled");
boolean enabled = enabledFeature == null
? false : enabledFeature.getValueAsBoolean(false);
FeatureResult rateFeature = config.getFeature("discount_rate");
double rate = rateFeature == null ? 0.0 : rateFeature.getValueAsDouble(0.0);
JSONObject defaults = new JSONObject();
defaults.put("theme", "default");
FeatureResult pageFeature = config.getFeature("page_config");
com.alibaba.fastjson2.JSONObject page = pageFeature == null
? defaults : pageFeature.getValueAsJson(defaults);
The read methods for all four types provide no-argument overloads, which return null when a value is missing or cannot be converted. Overloads with an argument return the specified default value. JSON uses Fastjson2's JSONObject. Boolean reads recognize Boolean values and true/false strings; other values fall back to the default. Your service still needs to handle exceptions thrown when configuration requests fail. Type default values do not replace network exception handling.
4.4 Retrieve Experiment Information
if (feature != null && feature.isExperimentMatched()) {
ExperimentInfo info = feature.getExperimentInfo();
String experimentId = info.fetchId();
String groupId = info.fetchGroupId();
boolean controlGroup = info.isControlGroup();
String featureKey = feature.getFeatureKey();
String featureVersion = feature.getFeatureVersion();
}
hasValue() indicates whether the current Feature has a value; isExperimentMatched() indicates whether it contains valid experiment information. A default value from the AE console may still be returned when no experiment is matched, in which case getExperimentInfo() is null. Reading only experiment information or calling hasValue()/isExperimentMatched() does not trigger automatic exposure tracking.
4.5 Retrieve All Configurations Visible to the Current Request
FeatureConfig all = client.fetch("user_123", "visitor_456");
Set<String> keys = all.getFeatureKeys();
When no Feature Key is specified, the SDK retrieves all configurations returned by the server for the current identity and request conditions.
4.6 Custom Request Parameters
FeatureConfig config = client.fetch(FeatureRequest.builder()
.accountId("user_123")
.featureKey("checkout_button")
.customParam("vip_level", 3)
.customParam("channel", "app_store")
.build());
Use customParam(key, value) to add a parameter, or customParams(Map<String, Object>) to pass parameters in bulk. Parameter names, types, and meanings should match the configuration channel and rule definitions in the AE console. Identity, SDK identifiers, and Key filtering are managed through dedicated parameters. Do not override #account_id, #distinct_id, #lib, or #feature_key through custom parameters. Custom request parameters do not set a new allocation subject.
5. Upload Exposure Events
An exposure means that an experiment configuration has actually been used in your service. Initiating fetch, returning FeatureConfig, or viewing experiment metadata alone does not mean that the configuration has been used. The SDK uploads te_experiment_exposure events through the data collection instance, with information about the experiment, group, Feature, and other details.
5.1 Manual Exposure Tracking (Default)
Keep automaticExposureTracking(false) during initialization. After your service actually uses the configuration, pass the FeatureResult retrieved in this request. The exposure API takes a result object, rather than a Feature Key string.
// feature must come from the current user's fetch result for this request
// Your service must have actually used this Feature's configuration value before this point
if (feature != null && feature.hasValue() && feature.isExperimentMatched()) {
Map<String, Object> properties = new HashMap<>();
properties.put("scene", "checkout");
client.exposure(feature, properties);
// Use client.exposure(feature) when custom properties are not needed
}
In custom exposure properties, property names beginning with # are reserved by the SDK and are ignored if passed in. The SDK skips results that do not contain valid experiment information.
5.2 Automatic Exposure Tracking (Optional)
When automaticExposureTracking is set to true, the first call to getValue() or getValueAsString/Double/Boolean/Json(...) on a result triggers automatic exposure tracking, provided that the result matches an experiment.
TDFeatureClient automaticClient = new TDFeatureClient(Config.builder()
.appId("YOUR_APP_ID")
.serverUrl("https://YOUR_RCC_SERVER")
.splitMode(SplitMode.REMOTE)
.tdAnalytics(analytics)
.automaticExposureTracking(true)
.build());
// Reuse automaticClient within the application and call close() only when the application exits
FeatureConfig config = automaticClient.fetch(FeatureRequest.builder()
.accountId("user_123")
.featureKey("checkout_button")
.build());
FeatureResult result = config.getFeature("checkout_button");
String value = result == null ? "control" : result.getValueAsString("control");
// If an experiment is matched, the value read above triggers exposure tracking
5.3 Deduplication, Asynchronous Sending, and Flushing
Exposure events are processed asynchronously in the SDK's background queue. The return of exposure(...) does not mean that the event has been stored in the database. By default, deduplication uses "allocation subject + experiment ID + group ID" in the current Client's in-memory cache, retaining up to 100000 markers with a default validity period of 86400 seconds. Events may be uploaded again after entries are evicted due to the deduplication cache capacity limit, the Client is recreated, or the process restarts;
// Call as needed for troubleshooting, at the end of short-lived tasks, or before the application exits
client.flush();
flush() waits for previously accepted exposure tasks and triggers the data collection SDK's flush.
6. Retrieve Configuration Asynchronously
The asynchronous overloads also require a FeatureRequest. The default asynchronous thread count is 5, and the default waiting queue capacity is 1000. A RejectedExecutionException occurs when the queue is full or the Client is closed. Fall back to the business default value and log the exception.
6.1 Future
FeatureRequest request = FeatureRequest.builder()
.accountId("user_123")
.featureKey("checkout_button")
.build();
Future<FeatureConfig> future = client.fetchAsync(request);
String value = "control";
try {
FeatureConfig config = future.get(2, TimeUnit.SECONDS);
FeatureResult result = config.getFeature("checkout_button");
if (result != null) {
value = result.getValueAsString("control");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (java.util.concurrent.TimeoutException
| java.util.concurrent.ExecutionException e) {
// Log the failure; value retains the business default
System.err.println("Asynchronous fetch failed: " + e.getMessage());
}
6.2 Callback
client.fetchAsync(FeatureRequest.builder()
.accountId("user_123")
.featureKey("checkout_button")
.build(), new FeatureCallback() {
@Override
public void onSuccess(FeatureConfig config) {
FeatureResult result = config.getFeature("checkout_button");
String value = result == null
? "control" : result.getValueAsString("control");
// Pass the configuration to your service; trigger manual exposure tracking after it is actually used
}
@Override
public void onFailure(Exception e) {
// Log the failure and continue using the business default value
System.err.println("Asynchronous fetch failed: " + e.getMessage());
}
});
7. Configuration Cache
The configuration cache is disabled by default. After enableCache(true) is enabled, subsequent calls with the same effective request can reuse the cached configuration response. Request identity, the set of Feature Keys, and custom request parameters all distinguish cache entries. The cache does not poll in the background: calls can return directly while the cache is valid, and RCC is accessed again on the next request after the cache expires.
TDFeatureClient cachedClient = new TDFeatureClient(Config.builder()
.appId("YOUR_APP_ID")
.serverUrl("https://YOUR_RCC_SERVER")
.splitMode(SplitMode.REMOTE)
.tdAnalytics(analytics)
.enableCache(true)
.cacheExpireTime(300)
.maxCacheSize(10000)
.build());
// Clear only the current Client's configuration cache
cachedClient.clearCache();

