Java Server SDK
Installation
Requirements
- Java 8 or higher
- Compatible with all platforms listed in the Supported OS and Architecture Combinations section, including:
- macOS (x86_64, arm64)
- Windows (x86_64, arm64, i686)
- Amazon Linux 2 and 2023 (x86_64, arm64)
Overview
The Statsig Java SDK consists of two parts that must be installed:
- The platform-independent core library (required for all installations)
- An OS/architecture-specific native library (required for your specific platform)
Installation Steps
Step 1: Install Core Library
- Gradle
- Maven
Add the following to your build.gradle
file:
repositories {
mavenCentral()
}
dependencies {
implementation 'com.statsig:javacore:X.X.X' // Replace X.X.X with the latest version
}
You can find the latest version on Maven Central.
Add the following to your pom.xml
file:
<dependencies>
<dependency>
<groupId>com.statsig</groupId>
<artifactId>javacore</artifactId>
<version>X.X.X</version> <!-- Replace X.X.X with the latest version -->
</dependency>
</dependencies>
You can find the latest version on Maven Central.
Step 2: Install Platform-Specific Library
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:
import com.statsig.*;
// All StatsigOptions are optional, feel free to adjust them as needed
StatsigOptions options = new StatsigOptions.Builder().build();
Statsig statsig = new Statsig("your-secret-key", options);
You'll receive output similar to:
For Linux with arm64 architecture, add the following to build.gradle:
implementation 'com.statsig:javacore:<version>:amazonlinux2023-arm64'
For Linux with x86_64 architecture, add the following to build.gradle:
implementation 'com.statsig:javacore:<version>:amazonlinux2023-x86_64'
Method 2: Manual Configuration
- Gradle
- Maven
Add the appropriate dependency to your build.gradle
file based on your system:
dependencies {
implementation 'com.statsig:javacore:X.X.X' // Core SDK (from Step 1)
implementation 'com.statsig:javacore:X.X.X:YOUR-OS-ARCHITECTURE' // OS/architecture-specific dependency
}
Add the appropriate dependency to your pom.xml
file based on your system:
<dependencies>
<dependency>
<groupId>com.statsig</groupId>
<artifactId>javacore</artifactId>
<version>X.X.X</version>
</dependency>
<dependency>
<groupId>com.statsig</groupId>
<artifactId>javacore</artifactId>
<version>X.X.X</version>
<classifier>YOUR-OS-ARCHITECTURE</classifier>
</dependency>
</dependencies>
Replace YOUR-OS-ARCHITECTURE
with one of the supported combinations from the Supported OS and Architecture Combinations section.
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
options
that allows you to pass in a StatsigOptions to customize the SDK.Initialize the SDK
After installation, you will need to initialize the SDK with customized Configuration using a Server Secret Key from the statsig console.
import com.statsig.*;
// All StatsigOptions are optional, feel free to adjust them as needed
StatsigOptions options = new StatsigOptions.Builder()
.setSpecsSyncIntervalMs(10000)
.setEventLoggingFlushIntervalMs(10000)
.setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
.build();
Statsig myStasigServer = new Statsig(SECRET_KEY, options);
statsig.initialize().get();
initialize
will perform a network request. After initialize
completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.Working with the SDK
Checking a Feature Flag/Gate
Now that your SDK is initialized, let's fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;
) by default.
From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:
boolean isFeatureOn = statsig.checkGate(user, "example_gate");
Reading a Dynamic Config
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
Difference between Experiment & DynamicConfig class
In this SDK, we now have two classes: Experiment and DynamicConfig, both of which help you manage feature flags and configurations for your users. These classes are similar to the ones in the Kotlin SDK, but are tailored for use in Java.
While both Experiment
and DynamicConfig
classes share similar functionalities (i.e., retrieving configuration values), their underlying structures and intended use cases differ slightly:
Config/Experiment Usage
DynamicConfig config = statsig.getDynamicConfig(user, "awesome_product_details");
Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
Layer layer = statsig.getLayer(user, "layer_name");
Experiment experiment = statsig.getExperiment(user, "sample_exp")
Parameter Stores
Sometimes - you don't know exactly what kind of Statsig config (Gate/Experiment/Layer/Dynamic Config) you want behind a particular value - you might want on-the-fly control of that, outside of your deployment cycle. Parameter Stores enable this by letting you define a "Parameter" - that can be static, or changed into a gate, experiment, etc. in the Statsig console. Parameter Stores are optional - but parameterizing your application can prove very useful, even allowing non-technical Statsig users to turn parameters into experiments.
Getting a Parameter Store
// Get a Parameter Store by name
ParameterStore parameterStore = statsig.getParameterStore(user, "my_parameter_store");
Retrieving Parameter Values
Parameter Store provides methods for retrieving values of different types with fallback defaults.
// String parameters
String stringValue = parameterStore.getString("string_param", "default_value");
// Boolean parameters
boolean boolValue = parameterStore.getBoolean("bool_param", false);
// Numeric parameters
double doubleValue = parameterStore.getDouble("double_param", 0.0);
int intValue = parameterStore.getInt("int_param", 0);
long longValue = parameterStore.getLong("long_param", 0L);
// Complex parameters
Map<String, Object> defaultMap = new HashMap<>();
defaultMap.put("key", "value");
Map<String, Object> mapValue = parameterStore.getMap("map_param", defaultMap);
Object[] defaultArray = new Object[]{"item1", "item2"};
Object[] arrayValue = parameterStore.getArray("array_param", defaultArray);
You can also use the Statsig instance directly:
String stringValue = statsig.getStringFromParameterStore(user, "my_parameter_store", "string_param", "default_value");
Logging an Event
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:
StatsigUser user = new StatsigUser("user123");
String eventName = "purchase";
String value = "100";
Map<String, String> metadata = new HashMap<>();
metadata.put("item_id", "12345");
metadata.put("category", "electronics");
statsig.logEvent(user, eventName, value, metadata);
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Retrieving Feature Gate Metadata
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:
FeatureGate gate = statsig.getFeatureGate(user, "exmaple_gate");
Manual Exposures
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Manual exposures give you the option to query your gates/experiments without triggering an exposure, and optionally, manually log the exposure after the fact.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
boolean result = statsig.checkGate(aUser, 'a_gate_name', new CheckGateOptions(true));
Later, if you would like to expose this gate, you can call the following.
statsig.manuallyLogGateExposure(aUser, 'a_gate_name');
To get a dynamic config without an exposure being logged, call the following.
DynamicConfig config = statsig.getDynamicConfig(aUser, 'a_dynamic_config_name', new CheckGateOptions(true));
Later, if you would like to expose the dynamic config, you can call the following.
statsig.manuallyLogDynamicConfigExposure(aUser, 'a_dynamic_config_name');
To get an experiment without an exposure being logged, call the following.
Experiment experiment = statsig.getExperiment(aUser, 'an_experiment_name', new CheckGateOptions(true));
Later, if you would like to expose the experiment, you can call the following.
statsig.manuallyLogExperimentExposure(aUser, 'an_experiment_name');
To get a layer parameter without an exposure being logged, call the following.
Layer layer = statsig.getLayer(aUser, 'a_layer_name', new CheckGateOptions(true));
const paramValue = layer.get('a_param_name', 'fallback_value');
Later, if you would like to expose the layer parameter, you can call the following.
statsig.manuallyLogLayerParamExposure(aUser, 'a_layer_name', 'a_param_name');
Statsig User
When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)
Besides userID
, we also have email
, ip
, userAgent
, country
, locale
and appVersion
as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom
field and be able to create targeting based on them.
Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.
Note that while typing is lenient on the StatsigUser
object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.
Usage in Java Core
StatsigUser user = new StatsigUser.Builder()
.setUserID("user_id")
.setCustomIDs(Map.of("external_id", "abc123"))
.setEmail("user@example.com")
.setIp("192.168.0.1")
.setLocale("en-US")
.setAppVersion("1.0.0")
.setUserAgent("Mozilla/5.0")
.setCountry("USA")
.setPrivateAttributes(Map.of("is_beta_user", "true"))
.setCustom(Map.of("subscription", "premium"))
.build();
Private Attributes
Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes
, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes
will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.
For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" }
to privateAttributes
on the user and that's it!
Statsig Options
StatsigOptions Class
The statsig.initialize()
method takes an optional parameter options
to customize the Statsig client. Below is the structure of the StatsigOptions
class, including available parameters and their descriptions:
Parameters
-
specsUrl
:Optional[str]
Custom URL for fetching feature specifications. -
specsSyncIntervalMs
:Optional[int]
How often the SDK updates specifications from Statsig servers (in milliseconds). -
initTimeoutMs
:Optional[int]
Sets the maximum timeout for initialization requests (in milliseconds). -
logEventUrl
:Optional[str]
Custom URL for logging events. -
disableNetwork
:Optional[bool]
Whentrue
, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called "localMode". -
disableAllLogging
:Optional[bool]
Whentrue
, disables all event logging. -
eventLoggingFlushIntervalMs
:Optional[int]
How often events are flushed to Statsig servers (in milliseconds). -
eventLoggingMaxQueueSize
:Optional[int]
Maximum number of events to queue before forcing a flush. -
enableIDLists
:Optional[bool]
Enable/disable ID list functionality. -
disableUserAgentParsing
Optional[bool]
Default false. If set to true, the SDK will NOT attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation. -
waitForUserAgentInit
Optional[bool]
Default: falseWhen set to true, the SDK will wait until user agent parsing data is fully loaded during initialization. This may slow down by ~1 second startup but ensures that parsing of the user’s userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations.
-
disableUserCountryLookup
Optional[bool]
Default false. If set to true, the SDK will NOT attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation. -
waitForCountryLookupInit
Optional[bool]
Default: falseWhen set to true, the SDK will wait for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down by ~1 second startup but ensures that IP-to-country parsing is ready at evaluation time
-
idListsUrl
:Optional[str]
Custom URL for fetching ID lists. -
idListsSyncIntervalMs
:Optional[int]
How often the SDK updates ID lists from Statsig servers (in milliseconds). -
environment
:Optional[str]
Environment parameter for evaluation. -
outputLoggerLevel
:Optional[OutputLogger.LogLevel]
Controls the verbosity of SDK logs. -
observabilityClient
:Optional<ObservabilityClient>
Interface for you to integrate observability metrics exposed by SDK, including, config propagation delay, initialization time spent. See details
Example Usage
from statsig import StatsigOptions
# Initialize StatsigOptions with custom parameters
options = StatsigOptions()
options.environment = "development"
options.init_timeout_ms = 3000
options.disable_all_logging = False
# Pass the options object into statsig.initialize()
statsig.initialize("secret-key", options)
Shutting Statsig Down
Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.
To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:
// Method signature
public CompletableFuture<Void> shutdown()
// example usage
try {
statsig.shutdown().get();
System.out.println("Statsig instance have been successfully shutdown.");
} catch (InterruptedException | ExecutionException e) {
System.err.println(e.getMessage());
}
// Method signature
public CompletableFuture<Void> flushEvents()
// example usage
try {
statsig.flushEvents().get();
System.out.println("All events have been successfully flushed.");
} catch (InterruptedException | ExecutionException e) {
System.err.println("Failed to flush events: " + e.getMessage());
}
Local Overrides
To override the return value of a gate/config/experiment/layer locally, we expose a set of override APIs. Coupling this with StatsigOptions.disable_network can be helpful when writing unit tests.
// Overrides the given gate to the specified value
statsig.overrideGate("a_gate_name", true);
// Overrides the given dynamic config to the provided value
statsig.overrideDynamicConfig("a_config_name", { key: "value" });
// Overrides the given experiment to the provided value
statsig.overrideExperiment("an_experiment_name", { key: "value" });
// Overrides the given layer to the provided value
statsig.overrideLayer("a_layer_name", { key: "value" });
// Overrides the given experiment to a particular groupname, available for experiments only:
statsig.overrideExperimentByGroupName("an_experiment_name", "a_group_name")
- These only apply locally - they do not update definitions in the Statsig console or elsewhere.
- The local override API is not designed to be a full mock. They are only a convenient way to override the value of the gate/config/etc.
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Additional Resources
- See the Supported OS and Architecture Combinations section for a complete list of platform-specific dependencies
- Check the Example Program section to verify your installation
- Review the Java Core vs Legacy Java SDK section if you're deciding which SDK to use
Java Core vs Legacy Java SDK
Statsig offers two Java SDKs:
- Java Core (Recommended) - A newer, performance-focused SDK with a shared Rust core library
- Legacy Java/Kotlin Server SDK - The original Java SDK (maintenance mode only)
Important: Moving forward, Statsig is focusing development efforts exclusively on the Java Core SDK. The Legacy Java SDK is in maintenance mode and will only receive critical bug fixes. All new features and improvements will only be available in the Java Core SDK.
Migration
If you're currently using the Legacy Java SDK and want to migrate to Java Core, follow these steps:
- Update your dependencies to use the Java Core library
- Replace imports from
com.statsig.sdk.*
tocom.statsig.*
- Update initialization code to use the new format
- Test your application thoroughly to ensure compatibility
Supported OS and Architecture Combinations
OS/Architecture Identifier | Description | Dependency |
---|---|---|
java-core | Platform-independent Java core, ALWAYS ADD THIS | implementation 'com.statsig:javacore:X.X.X' |
macos-arm64 | macOS (Apple Silicon/ARM64) | implementation 'com.statsig:javacore:X.X.X:macos-arm64' |
macos-x86_64 | macOS (Intel/x86_64 or AMD64) | implementation 'com.statsig:javacore:X.X.X:macos-x86_64' |
windows-arm64 | Windows (ARM64) | implementation 'com.statsig:javacore:X.X.X:windows-arm64' |
windows-i686 | Windows (Intel/i686, 32-bit architecture) | implementation 'com.statsig:javacore:X.X.X:windows-i686' |
windows-x86_64 | Windows (Intel/AMD 64-bit architecture, x86_64) | implementation 'com.statsig:javacore:X.X.X:windows-x86_64' |
amazonlinux2-arm64 | Amazon Linux 2 (ARM64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2-arm64' |
amazonlinux2-x86_64 | Amazon Linux 2 (Intel/AMD 64-bit, x86_64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2-x86_64' |
amazonlinux2023-arm64 | Amazon Linux 2023 (ARM64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2023-arm64' |
amazonlinux2023-x86_64 | Amazon Linux 2023 (Intel/AMD 64-bit, x86_64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2023-x86_64' |
Sample App
This sample shows a simple Java application using the Statsig Java Core SDK to check a feature flag.
Project Setup
- Gradle
- Maven
Create a build.gradle
file with:
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.statsig:javacore:X.X.X' // Replace with latest version
implementation 'com.statsig:javacore:X.X.X:YOUR-OS-ARCHITECTURE' // Replace with your OS/architecture
}
application {
mainClass = 'ExampleApp'
}
Create a pom.xml
file with:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>statsig-example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<exec.mainClass>ExampleApp</exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>com.statsig</groupId>
<artifactId>javacore</artifactId>
<version>X.X.X</version>
</dependency>
<dependency>
<groupId>com.statsig</groupId>
<artifactId>javacore</artifactId>
<version>X.X.X</version>
<classifier>YOUR-OS-ARCHITECTURE</classifier>
</dependency>
</dependencies>
</project>
Create Java Application
Create a file named ExampleApp.java
:
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("my_feature_gate", "user123");
System.out.println("Feature gate is " + (isEnabled ? "enabled" : "disabled"));
// Get a config
Config config = statsig.getConfig("my_config", "user123");
System.out.println("Config value: " + config.getValue("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
- Gradle
- Maven
./gradlew run
mvn compile exec:java
If everything is set up correctly, you should see output related to your feature gate and configuration.
Reference
FeatureGate Class Structure:
class FeatureGate {
String name; // gate name
boolean value; // evluation boolean result
String ruleID; // rule id for this gate
EvaluationDetails evaluationDetails; // evluation details
String rawJson; // in case you might intersted in a raw Json string of
// this feature gate
}
Experiment Class Structure:
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 within the experiment
EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated
String rawJson; // Raw JSON representation of the experiment
}
DynamicConfig Class Structure:
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
EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated
String rawJson; // Raw JSON representation of the experiment
}
Methods for both Experiment and DynamicConfig
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
Layer {
String name; // layer name
String ruleID; // rule id for this rule
String groupName;
Map<String, JsonElement> value;
String allocatedExperimentName;
EvaluationDetails evaluationDetails;
String rawJson; // raw JSON string representation of Layer Object
}
Layer Methods
/**
* Retrieves a string value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* String value = layer.getString("feature_name", "default_value");
*/
public String getString(String key, String fallbackValue)
/**
* Retrieves a boolean value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Boolean isEnabled = layer.getBoolean("is_enabled", false);
*/
public boolean getBoolean(String key, Boolean fallbackValue)
/**
* Retrieves a double value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* double ratio = layer.getDouble("conversion_ratio", 1.0);
*/
public double getDouble(String key, double fallbackValue)
/**
* Retrieves an integer value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* int maxAttempts = layer.getInt("max_attempts", 3);
*/
public int getInt(String key, int fallbackValue)
/**
* Retrieves a long value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* long timestamp = layer.getLong("start_timestamp", 1627389483L);
*/
public long getLong(String key, long fallbackValue)
/**
* Retrieves an array of objects from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Object[] items = layer.getArray("item_list", new Object[] {});
*/
public Object[] getArray(String key, Object[] fallbackValue)
/**
* Retrieves a Map object from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Map<String, Object> items = layer.getMap("item_list", new Object[] {});
*/
public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)