Migrating from the Legacy Java SDK? See our Migration Guide.
Setup the SDK
1
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
- 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.- Linux (x86_64, arm64)
- macOS (x86_64, arm64)
- Windows (x86_64)
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.1
Install Core Library
2
Install Platform-Specific Library
You need to add the appropriate OS/architecture-specific dependency. Choose one of the following methods:Method 1: Automatic DetectionRun the following code to detect your system and get the appropriate dependency:You’ll receive output similar to:Method 2: Manual ConfigurationReplace
YOUR-OS-ARCHITECTURE with one of the supported combinations from the Supported OS and Architecture Combinations section.Docker Considerations for Alpine LinuxWhen 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: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).Tested Platforms
Tested Platforms
Docker base images where the Java Core SDK has been tested and verified:
| Docker Base Image | Description |
|---|---|
| amazoncorretto:21 | Amazon Corretto 21 JDK |
| amazoncorretto:21-alpine-jdk | Amazon Corretto 21 JDK on Alpine Linux |
| amazonlinux:2 | Amazon Linux 2 |
| public.ecr.aws/amazonlinux/amazonlinux:2023 | Amazon Linux 2023 |
| azul/zulu-openjdk-alpine:21 | Azul Zulu OpenJDK 21 on Alpine Linux |
| azul/zulu-openjdk:21 | Azul Zulu OpenJDK 21 |
| eclipse-temurin:21-jdk | Eclipse Temurin 21 JDK |
| eclipse-temurin:21-jdk-alpine | Eclipse Temurin 21 JDK on Alpine Linux |
2
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.There is also an optional parameter named
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
options that allows you to pass in a StatsigOptions to customize the SDK.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.Getting Started
Quick Start Example
1
Create a new Java project
Create a new Gradle or Maven project with the following structure:
2
Add Statsig dependency
X.X.X with the latest version from Maven Central.3
Write your application code
YOUR_SERVER_SECRET_KEY with your actual server secret key from the Statsig Console.4
Run the application
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 (thinkreturn 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:
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 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:Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but often recommend the use of layers, which make parameters reusable and let you run mutually exclusive experiments.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:Parameter Stores
Sometimes you don’t know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments.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: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.Using Shared Instance
In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose: The Java SDK supports using a shared instance for convenience:Manual Exposures
By default, the SDK will automatically log an exposure event when you check a gate, get a config, get an experiment, or call get() on a parameter in a layer. However, there are times when you may want to log an exposure event manually. For example, if you’re using a gate to control access to a feature, but you don’t want to log an exposure until the user actually uses the feature, you can use manual exposures. Manual exposures allow you to control when exposure events are logged. This is useful when you want to delay exposure logging until certain conditions are met.Statsig User
TheStatsigUser 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, 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.
Private Attributes
Private attributes are user attributes that are used for evaluation but are not forwarded to any integrations. They are useful for PII or sensitive data that you don’t want to send to third-party services. TheStatsigUser object represents a user in your application and contains fields used for feature evaluation.
Private Attributes
Private attributes are fields that will be used for evaluation but will not be logged in events sent to Statsig servers.Statsig Options
You can pass in an optional parameteroptions in addition to sdkKey during initialization to customize the Statsig client. Here are the available options that you can configure.
StatsigOptions
StatsigOptions
Environment parameter for evaluation.
Custom URL for fetching feature specifications.
How often the SDK updates specifications from Statsig servers (in milliseconds).
Turn this on if you are proxying
download_config_specs / get_id_lists and want to fall back to the default Statsig endpoint to increase reliability.Custom URL for logging events.
If true, the SDK will not collect any logging within the session, including custom events and config check exposure events.
Required to be
true when using segments with more than 1000 IDs.If true, the SDK will not parse User-Agent strings into
browserName, browserVersion, systemName, systemVersion, and appVersion when needed for evaluation.If true, the SDK will not parse IP addresses (from
user.ip) into country codes when needed for evaluation.How often events are flushed to Statsig servers (in milliseconds).
Maximum number of events to queue before forcing a flush.
An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network.
Interface to use persistent storage within the SDK.
Set the logging level for the SDK. Options:
NONE, ERROR, WARN, INFO, DEBUG.Interface to integrate observability metrics exposed by the SDK.
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 callshutdown() before your app/server shuts down:
Local Overrides
Local Overrides are a way to override the values of gates, configs, experiments, and layers for testing purposes. This is useful for local development or testing scenarios where you want to force a specific value without having to change the configuration in the Statsig console. Local overrides allow you to override feature gate and config values for testing purposes.Persistent Storage
The Persistent Storage interface allows you to implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups even when the user returns later. This is particularly useful for client-side A/B testing where you want to ensure users always see the same variant. Persistent storage allows the SDK to cache feature specifications locally, enabling faster initialization and offline operation.Data Store
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems. Data stores allow you to customize how the SDK fetches and caches feature specifications, enabling advanced use cases like using Redis or other distributed caches.Custom Output Logger
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity. Custom output logger allows you to redirect SDK logs to your own logging system.Observability Client
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation. Observability client allows you to monitor SDK performance and emit custom metrics.FAQ
What Java versions are supported?
What Java versions are supported?
The Java Core SDK supports Java 8 and higher. Java 8 support was added in version 0.4.3.
Which platforms are supported?
Which platforms are supported?
The SDK supports:
- Linux (x86_64, arm64, musl variants)
- macOS (x86_64, arm64)
- Windows (x86_64)
Should I use the uber JAR or platform-specific JARs?
Should I use the uber JAR or platform-specific JARs?
The uber JAR is recommended for most use cases as it includes native libraries for all popular platforms and simplifies deployment. Use platform-specific JARs only if you need to minimize JAR size or have specific dependency requirements.
How do I use this with Alpine Linux?
How do I use this with Alpine Linux?
For Alpine Linux (musl-based systems), install compatibility packages:The SDK will automatically use musl-compatible native libraries.
How do I handle initialization in production?
How do I handle initialization in production?
The SDK initialization is asynchronous. Use Always call
.get() on the CompletableFuture to wait for initialization:shutdown() when your application terminates to flush pending events.Can I use multiple Statsig instances?
Can I use multiple Statsig instances?
Yes, you can create multiple Statsig instances with different configurations. You can also use the global singleton with
Statsig.getGlobalSingleton() for convenience.How do I debug SDK issues?
How do I debug SDK issues?
Set the output logger level to DEBUG to see detailed logs:
Reference
FeatureGate Class
Experiment Class
DynamicConfig Class
Layer Class
Fields Needed Methods (Enterprise Only)
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our slack channel if you want this enabled.