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.
Copy
repositories { mavenCentral()}dependencies { implementation 'com.statsig:javacore:X.X.X:uber' // Uber JAR with all native libraries}
You can find the latest version on Maven Central.The uber JAR includes native libraries for:
Linux (x86_64, arm64)
macOS (x86_64, arm64)
Windows (x86_64)
This approach eliminates the need to specify the exact platform and simplifies deployment across different environments.
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
Copy
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 DetectionRun the following code to detect your system and get the appropriate dependency:
Copy
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:
Copy
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 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:
Copy
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).
Tested Platforms
Docker base images where the Java Core SDK has been tested and verified:
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
Copy
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 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.
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:
Copy
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");
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:
Copy
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");
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.
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:
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.
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:
Copy
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);
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.
Copy
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);
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:
Copy
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();
The shared instance functionality provides a singleton pattern where a single Statsig instance can be created and accessed globally throughout your application. This is useful for applications that need to access Statsig functionality from multiple parts of the codebase without having to pass around a Statsig instance.
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.
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.
Copy
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");
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, 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. As explained here, at least one identifier (userID or customID) is required to provide a consistent experience for a given user.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 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.The StatsigUser object represents a user in your application and contains fields used for feature evaluation.
Copy
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");
You can pass in an optional parameter options in addition to sdkKey during initialization to customize the Statsig client. Here are the available options that you can configure.
If true, the SDK will not parse User-Agent strings into browserName, browserVersion, systemName, systemVersion, and appVersion when needed for evaluation.
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 call shutdown() before your app/server shuts down:
Copy
// 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 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.
Copy
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");
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 persist sticky experiment assignments for users, ensuring they see consistent experiment variants across sessions.
Copy
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();
The PersistentStorage interface provides helper methods for working with user-based storage keys:
Copy
// 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"
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.
Copy
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();
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.
Copy
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();
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.
Copy
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();
The Java Core SDK supports Java 8 and higher. Java 8 support was added in version 0.4.3.
Which platforms are supported?
The SDK supports:
Linux (x86_64, arm64, musl variants)
macOS (x86_64, arm64)
Windows (x86_64)
See the Tested Platforms section for verified Docker images.
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?
For Alpine Linux (musl-based systems), install compatibility packages:
Copy
RUN apk add --no-cache libgcc gcompat
The SDK will automatically use musl-compatible native libraries.
How do I handle initialization in production?
The SDK initialization is asynchronous. Use .get() on the CompletableFuture to wait for initialization:
Copy
Statsig statsig = new Statsig("secret-key", options);statsig.initialize().get(); // Blocks until initialized
Always call shutdown() when your application terminates to flush pending events.
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?
Set the output logger level to DEBUG to see detailed logs:
Copy
StatsigOptions options = new StatsigOptions.Builder() .setOutputLoggerLevel(OutputLogger.LogLevel.DEBUG) .build();
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}
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:
Copy
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)
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:
Copy
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)
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:
Copy
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)
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our Slack community if you want this enabled.
These methods allow you to retrieve a list of user fields that are used in the targeting rules for gates, configs, experiments, and layers.
Copy
// 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 MappingThe fields returned by these methods correspond to the following user properties:
Copy
// 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"