Migrating from the Legacy Java SDK? Refer to the Migration Guide.
Setup the SDK
Install the SDK
Requirements
Java 8 or higher (Java 8 support added in version 0.4.3)
Compatible with all platforms listed in the Supported OS and Architecture Combinations section, including:
macOS (x86_64, arm64)
Windows (x86_64)
Amazon Linux 2 and 2023 (x86_64, arm64)
Overview
The Statsig Java SDK can be installed in two ways:
Recommended: Single JAR installation (since version 0.4.0)
Use the "uber" JAR which contains both the core library and popular platform-specific native libraries in a single package
Simplifies dependency management and deployment across different environments
Advanced: Two-part installation
The platform-independent core library
An OS/architecture-specific native library for your specific platform
Installation steps
Recommended: Using the Uber JAR (All-in-One)
Since version 0.4.0, Statsig provides an "uber" JAR that contains both the core library and native libraries for popular supported platforms in a single package. This is the recommended approach for most users.
repositories { mavenCentral()}dependencies { implementation 'com.statsig:javacore:X.X.X:uber' // Uber JAR with all native libraries}
This approach eliminates the need to specify the exact platform and simplifies deployment across different environments.
Advanced: Platform-specific installation
If you need more control over dependencies or want to minimize the JAR size for a specific platform, you can use the platform-specific installation approach.
Install Core Library
repositories { mavenCentral()}dependencies { implementation 'com.statsig:javacore:X.X.X' // Replace X.X.X with the latest version}
You need to add the appropriate OS/architecture-specific dependency. Choose one of the following methods:
Method 1: Automatic Detection
Run the following code to detect your system and get the appropriate dependency:
java
import com.statsig.*;// All StatsigOptions are optional, feel free to adjust them as neededStatsigOptions options = new StatsigOptions.Builder().build();Statsig statsig = new Statsig("your-secret-key", options);
You'll receive output similar to:
plaintext
For Linux with arm64 architecture, add the following to build.gradle: implementation 'com.statsig:javacore:<version>:aarch64-unknown-linux-gnu'For Linux with x86_64 architecture, add the following to build.gradle: implementation 'com.statsig:javacore:<version>:x86_64-unknown-linux-gnu'
Replace YOUR-OS-ARCHITECTURE with one of the supported combinations from the Supported OS and Architecture Combinations section.
Docker Considerations for Alpine Linux
When using Alpine Linux or other musl-based Docker containers, you need to install additional compatibility packages for the native libraries to work properly. Add the following to your Dockerfile:
dockerfile
RUN apk add --no-cache libgcc gcompat
The Statsig Java Core SDK automatically detects musl-based systems and will use the appropriate musl-compatible native libraries (e.g., x86_64-unknown-linux-musl, aarch64-unknown-linux-musl).
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
An optional options parameter accepts a StatsigOptions object to customize the SDK.
import com.statsig.*;// All StatsigOptions are optional, feel free to adjust them as neededStatsigOptions options = new StatsigOptions.Builder() .setSpecsSyncIntervalMs(10000) .setEventLoggingFlushIntervalMs(10000) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build();Statsig myStatsigServer = new Statsig(SECRET_KEY, options);myStatsigServer.initialize().get();
initialize performs a network request. After initialize completes, virtually all SDK operations are synchronous (refer to Evaluating Feature Gates in the Statsig SDK). The SDK fetches updates from Statsig in the background, independent of your API calls.
Getting started
Quick start example
Create a new Java project
Create a new Gradle or Maven project with the following structure:
plugins { id 'java' id 'application'}repositories { mavenCentral()}dependencies { implementation 'com.statsig:javacore:X.X.X:uber'}application { mainClass = 'ExampleApp'}
Replace X.X.X with the latest version from Maven Central.
Write your application code
import com.statsig.*;public class ExampleApp { public static void main(String[] args) throws Exception { // Initialize Statsig StatsigOptions options = new StatsigOptions.Builder().build(); Statsig statsig = new Statsig("YOUR_SERVER_SECRET_KEY", options); statsig.initialize().get(); try { // Check a feature gate boolean isEnabled = statsig.checkGate("user123", "my_feature_gate"); System.out.println("Feature gate is " + (isEnabled ? "enabled" : "disabled")); // Get a config DynamicConfig config = statsig.getConfig("user123", "my_config"); System.out.println("Config value: " + config.getString("some_parameter", "default_value")); } finally { // Always shutdown Statsig when done statsig.shutdown(); } }}
Replace YOUR_SERVER_SECRET_KEY with your actual server secret key from the Statsig Console.
Run the application
./gradlew run
If everything is set up correctly, you should see output related to your feature gate and configuration.
Working with the SDK
Checking a Feature Flag/Gate
After the SDK is initialized, you can fetch a Feature Gate. Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are CLOSED or OFF (equivalent to return false;) by default.All APIs require a user object (refer to Statsig user). To check a gate for a user:
String userID = "user_id";boolean result = statsig.checkGate(userID, "my_feature_gate");// with StatsigUserStatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build();boolean gateResult = statsig.checkGate(user, "my_feature_gate");
Reading a Dynamic Config
Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use Dynamic Configs. The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example:
String userID = "user_id";DynamicConfig config = statsig.getConfig(userID, "my_config");String name = config.getString("name", "");int size = config.getInt("size", 10);// with StatsigUserStatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build();DynamicConfig dynamicConfig = statsig.getConfig(user, "my_config");
Getting a Layer/Experiment
Layers/Experiments let you run A/B/n experiments. Two APIs are available, but layers are recommended because layers make parameters reusable and support mutually exclusive experiments.
If you want dynamic control over whether a value comes from a Feature Gate, Experiment, or Dynamic Config outside your deployment cycle, use Parameter Stores. A Parameter Store lets you define a parameter that you can change at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application supports future flexibility and allows non-technical Statsig users to turn parameters into experiments.
After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata:
import java.util.HashMap;import java.util.Map;String userID = "user_id";String eventName = "my_custom_event";// Simple eventstatsig.logEvent(userID, eventName);// Event with valuestatsig.logEvent(userID, eventName, 10.5);// Event with metadataMap<String, String> metadata = new HashMap<>();metadata.put("key1", "value1");metadata.put("key2", "value2");statsig.logEvent(userID, eventName, metadata);// Event with value and metadatastatsig.logEvent(userID, eventName, 10.5, metadata);// with StatsigUserStatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build();statsig.logEvent(user, eventName, 10.5, metadata);
Sending events to Log Explorer
You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log.
import java.util.HashMap;import java.util.Map;String userID = "user_id";Map<String, Object> payload = new HashMap<>();payload.put("log_level", "error");payload.put("message", "Something went wrong");payload.put("timestamp", System.currentTimeMillis());statsig.forwardLogLineEvent(userID, payload);// with StatsigUserStatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build();statsig.forwardLogLineEvent(user, payload);
Using shared instance
To access a single Statsig instance globally throughout your codebase, use the shared instance singleton pattern:
import com.statsig.*;// Create a shared instance that can be accessed globallyStatsigServer statsig = Statsig.newShared("secret-key");statsig.initialize().get();// Access the shared instance from anywhere in your codeStatsigServer sharedStatsig = Statsig.shared();boolean isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name");// Check if a shared instance existsif (Statsig.hasSharedInstance()) { // Use the shared instance}// Remove the shared instance when no longer neededStatsig.removeShared();
Statsig.newShared(sdkKey, options): Creates a new shared instance of Statsig that can be accessed globally
Statsig.shared(): Returns the shared instance
Statsig.hasSharedInstance(): Checks if a shared instance exists (useful when you aren't sure if the shared instance is ready yet)
Statsig.removeShared(): Removes the shared instance (useful when you want to switch to a new shared instance)
hasSharedInstance() and removeShared() are helpful in specific scenarios but aren't required in most use cases where the shared instance is set up near the top of your application.
Also note that only one shared instance can exist at a time. Attempting to create a second shared instance will result in an error.
Manual exposures
By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call get() on a layer parameter. To delay exposure logging until the user actually uses the feature, use manual exposures.
String userID = "user_id";// Check gate without logging exposureboolean result = statsig.checkGateWithExposureLoggingDisabled(userID, "my_feature_gate");// Manually log the exposure when readystatsig.manuallyLogGateExposure(userID, "my_feature_gate");// Works with configs tooDynamicConfig config = statsig.getConfigWithExposureLoggingDisabled(userID, "my_config");statsig.manuallyLogConfigExposure(userID, "my_config");// And with experiments/layersExperiment experiment = statsig.getExperimentWithExposureLoggingDisabled(userID, "my_experiment");statsig.manuallyLogExperimentExposure(userID, "my_experiment");Layer layer = statsig.getLayerWithExposureLoggingDisabled(userID, "my_layer");statsig.manuallyLogLayerParameterExposure(userID, "my_layer", "parameter_name");
Statsig User
The StatsigUser object represents a user in Statsig. You must provide a userID or at least one of the customIDs to identify the user.
When calling APIs that require a user, pass as much information as possible to enable advanced gate and config conditions (such as country or OS/browser checks) and to measure experiment impact accurately. As explained in why an ID is always required for server SDKs, at least one identifier (userID or customID) is required to provide a consistent experience for a given user.
In addition to userID, the top-level fields on StatsigUser are: email, ip, userAgent, country, locale, and appVersion. You can also pass key-value pairs in the custom field for targeting.
Private attributes
Private attributes are user attributes used for evaluation but not forwarded to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services.
import com.statsig.*;import java.util.HashMap;import java.util.Map;// Build a user with various fieldsMap<String, Object> customFields = new HashMap<>();customFields.put("plan", "premium");customFields.put("age", 25);Map<String, String> privateAttributes = new HashMap<>();privateAttributes.put("internal_id", "123456");StatsigUser user = StatsigUser.builder() .userID("user_123") .email("user@example.com") .ip("192.168.1.1") .userAgent("Mozilla/5.0...") .country("US") .locale("en_US") .appVersion("1.2.3") .custom(customFields) .privateAttributes(privateAttributes) .build();// Use the user for evaluationboolean result = statsig.checkGate(user, "my_feature_gate");
Private attributes
Statsig evaluates private attributes normally but doesn't log them in events sent to Statsig servers. Use them for PII or other sensitive data.
Map<String, String> privateAttributes = new HashMap<>();privateAttributes.put("sensitive_field", "sensitive_value");StatsigUser user = StatsigUser.builder() .userID("user_123") .privateAttributes(privateAttributes) .build();
Statsig Options
You can pass an optional options parameter in addition to sdkKey during initialization to customize the Statsig client.
Proxy and custom network routing
Use setProxyConfig(ProxyConfig) if your service needs a standard outbound HTTP proxy for Statsig network calls. Use setSpecAdapterConfigs(...) if you are routing spec downloads through Statsig Forward Proxy.
java
ProxyConfig proxyConfig = new ProxyConfig();proxyConfig.setProxyHost("proxy.example.com");proxyConfig.setProxyPort(8080);proxyConfig.setProxyProtocol("https");proxyConfig.setCaCertPath("/etc/ssl/certs/corporate-ca.pem"); // OptionalStatsigOptions options = new StatsigOptions.Builder() .setProxyConfig(proxyConfig) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
ProxyConfig supports proxyHost, proxyPort, proxyAuth, proxyProtocol, and caCertPath. Set caCertPath when your environment requires a custom PEM CA bundle for outbound TLS.
Statsig Forward Proxy example
java
import java.util.Collections;SpecAdapterConfig forwardProxyConfig = new SpecAdapterConfig() .setAdapterType(SpecAdapterType.NETWORK_GRPC_WEBSOCKET) .setSpecsUrl("http://forward-proxy.internal:50051") .setAuthenticationMode(AuthenticationMode.NONE);StatsigOptions options = new StatsigOptions.Builder() .setSpecAdapterConfigs(Collections.singletonList(forwardProxyConfig)) .setFallbackToStatsigApi(true) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
Shutting Statsig Down
Because events are batched and periodically flushed, some events may not have been sent when your app or server shuts down. To ensure all logged events are flushed, call shutdown() before shutting down your app or server:
// Shutdown flushes all pending events and stops background tasksstatsig.shutdown();// Or with a timeout (blocks until shutdown completes or timeout)statsig.shutdown().get(5, TimeUnit.SECONDS);
Local overrides
Local Overrides let you override the values of gates, configs, experiments, and layers for testing purposes, without changing the configuration in the Statsig console.
import java.util.HashMap;import java.util.Map;// Override a gatestatsig.overrideGate("my_feature_gate", true);// Override a configMap<String, Object> configOverride = new HashMap<>();configOverride.put("key", "value");configOverride.put("number", 42);statsig.overrideConfig("my_config", configOverride);// Override an experimentMap<String, Object> experimentOverride = new HashMap<>();experimentOverride.put("variant", "test");statsig.overrideExperiment("my_experiment", experimentOverride);// Override an experiment to a particular groupnamestatsig.overrideExperimentByGroupName("my_experiment", "a_group_name");statsig.overrideExperimentByGroupName("my_experiment", "a_group_name", "user_123");// Override a layerMap<String, Object> layerOverride = new HashMap<>();layerOverride.put("layer_param", "override_value");statsig.overrideLayer("my_layer", layerOverride);// Clear all overridesstatsig.clearAllOverrides();// Clear specific overridestatsig.clearGateOverride("my_feature_gate");statsig.clearConfigOverride("my_config");
Persistent storage
The Persistent Storage interface lets you implement custom storage for user-specific configurations. Use it to persist user assignments across sessions, ensuring consistent experiment groups when users return. This is useful for client-side A/B testing where you need users to always see the same variant.
import com.statsig.*;import java.util.HashMap;import java.util.Map;class MyPersistentStorage implements PersistentStorage { private Map<String, Map<String, StickyValues>> storage = new HashMap<>(); @Override public Map<String, StickyValues> load(String key) { // Load persisted sticky values for the given key // Key format is "{userId}:userID" or "{customId}:{idType}" return storage.get(key); } @Override public void save(String key, String configName, StickyValues data) { // Save sticky values for a specific experiment/config storage.computeIfAbsent(key, k -> new HashMap<>()).put(configName, data); } @Override public void delete(String key, String configName) { // Delete sticky values for a specific experiment/config Map<String, StickyValues> values = storage.get(key); if (values != null) { values.remove(configName); } }}// Use persistent storageStatsigOptions options = new StatsigOptions.Builder() .setPersistentStorage(new MyPersistentStorage()) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
Helper methods
The PersistentStorage interface provides helper methods for working with user-based storage keys:
java
// Get persisted values for a user using the helper methodMap<String, StickyValues> values = persistentStorage.getValuesForUser(user, "userID");// Generate a storage key from a user and ID typeString key = PersistentStorage.getStorageKey(user, "userID"); // Returns "{userId}:userID"String customKey = PersistentStorage.getStorageKey(user, "companyID"); // Returns "{companyId}:companyID"
Data store
The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems such as Redis.
import com.statsig.*;class MyDataStore implements DataStore { @Override public String getDataSync(String key) { // Synchronously fetch data for the given key // This is called during SDK evaluation return null; } @Override public CompletableFuture<Void> setData(String key, String data) { // Store data for the given key // Called when SDK receives updates from Statsig return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> initialize() { // Perform any initialization needed for your data store return CompletableFuture.completedFuture(null); } @Override public void shutdown() { // Clean up resources }}// Use data storeStatsigOptions options = new StatsigOptions.Builder() .setDataStore(new MyDataStore()) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
Custom output logger
The Output Logger interface lets you customize how the SDK logs messages and enables integration with your own logging system and control over log verbosity.
import com.statsig.*;class MyOutputLogger implements OutputLogger { @Override public void log(LogLevel level, String message) { // Route SDK logs to your logging system switch (level) { case ERROR: System.err.println("[ERROR] " + message); break; case WARN: System.out.println("[WARN] " + message); break; case INFO: System.out.println("[INFO] " + message); break; case DEBUG: System.out.println("[DEBUG] " + message); break; } }}// Use custom output loggerStatsigOptions options = new StatsigOptions.Builder() .setOutputLogger(new MyOutputLogger()) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
Observability client
The Observability Client interface lets you monitor SDK health by integrating with your own observability systems. For more information on the metrics emitted by Statsig SDKs, go to the Monitoring documentation.
import com.statsig.*;class MyObservabilityClient implements ObservabilityClient { @Override public void emitMetric(String metricName, double value, Map<String, String> tags) { // Send metric to your monitoring system System.out.println("Metric: " + metricName + " = " + value + ", tags: " + tags); } @Override public void startTimer(String operationName) { // Start timing an operation } @Override public void endTimer(String operationName, Map<String, String> tags) { // End timing and emit duration metric }}// Use observability clientStatsigOptions options = new StatsigOptions.Builder() .setObservabilityClient(new MyObservabilityClient()) .build();Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get();
FAQ
Reference
FeatureGate Class
java
class FeatureGate { String name; // Gate name boolean value; // Evaluation boolean result String ruleID; // Rule ID for this gate EvaluationDetails evaluationDetails; // Evaluation details String rawJson; // Raw JSON string representation}
Experiment Class
java
class Experiment { String name; // Name of the experiment String ruleID; // ID of the rule used in the experiment Map<String, JsonElement> value; // Configuration values specific to the experiment String groupName; // The group name the user falls into EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated String rawJson; // Raw JSON representation of the experiment}
Methods for Experiment:
java
public String getString(String key, String fallbackValue)public boolean getBoolean(String key, Boolean fallbackValue)public double getDouble(String key, double fallbackValue)public int getInt(String key, int fallbackValue)public long getLong(String key, long fallbackValue)public Object[] getArray(String key, Object[] fallbackValue)public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)
DynamicConfig Class
java
class DynamicConfig { String name; // Name of the config String ruleID; // ID of the rule used Map<String, JsonElement> value; // Configuration values EvaluationDetails evaluationDetails; // Details about how the config was evaluated String rawJson; // Raw JSON representation}
Methods for DynamicConfig:
java
public String getString(String key, String fallbackValue)public boolean getBoolean(String key, Boolean fallbackValue)public double getDouble(String key, double fallbackValue)public int getInt(String key, int fallbackValue)public long getLong(String key, long fallbackValue)public Object[] getArray(String key, Object[] fallbackValue)public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)
Layer Class
java
class Layer { String name; // Layer name String ruleID; // Rule ID for this layer String groupName; // Group name Map<String, JsonElement> value; // Layer values String allocatedExperimentName; // Allocated experiment name EvaluationDetails evaluationDetails; // Evaluation details String rawJson; // Raw JSON string representation}
Methods for Layer:
java
public String getString(String key, String fallbackValue)public boolean getBoolean(String key, Boolean fallbackValue)public double getDouble(String key, double fallbackValue)public int getInt(String key, int fallbackValue)public long getLong(String key, long fallbackValue)public Object[] getArray(String key, Object[] fallbackValue)public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)
Fields needed methods (Enterprise only)
This is available for Enterprise contracts. Reach out to our support team, your sales contact, or through our Slack community to enable it.
These methods let you retrieve a list of user fields used in the targeting rules for gates, configs, experiments, and layers.
java
// Get user fields needed for a gate evaluationList<String> getFieldsNeededForGate(String gateName)// Get user fields needed for a dynamic config evaluationList<String> getFieldsNeededForDynamicConfig(String configName)// Get user fields needed for an experiment evaluationList<String> getFieldsNeededForExperiment(String experimentName)// Get user fields needed for a layer evaluationList<String> getFieldsNeededForLayer(String layerName)
Field Mapping
The fields returned by these methods correspond to the following user properties:
java
// Field mapping between user properties and internal field namesuserID -> "u"email -> "e"ip -> "i"userAgent -> "ua"country -> "c"locale -> "l"appVersion -> "a"time -> "t"stableID -> "s"environment -> "en"targetApp -> "ta"// Custom fields are prefixed with "cf:"// Example: "cf:plan", "cf:age"