
{% callout type="tip" %}
Migrating from the Legacy Java SDK? Refer to the

[Migration Guide](/server-core/migration-guides/java)

.
{% /callout %}

## Setup the SDK

{% steps %}
{% step title="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**

1. The platform-independent core library
2. 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.

{% codetabs %}
```groovy Gradle
repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.statsig:javacore:X.X.X:uber' // Uber JAR with all native libraries
}
```

```xml Maven
<dependencies>
    <dependency>
        <groupId>com.statsig</groupId>
        <artifactId>javacore</artifactId>
        <version>X.X.X</version>
        <classifier>uber</classifier>
    </dependency>
</dependencies>
```
{% /codetabs %}

You can find the latest version on [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore).

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.

### 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.

{% steps %}
{% step title="Install Core Library" %}
{% codetabs %}
```groovy Gradle
repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.statsig:javacore:X.X.X'  // Replace X.X.X with the latest version
}
```

```xml Maven
<dependencies>
    <dependency>
        <groupId>com.statsig</groupId>
        <artifactId>javacore</artifactId>
        <version>X.X.X</version>  <!-- Replace X.X.X with the latest version -->
    </dependency>
</dependencies>
```
{% /codetabs %}

You can find the latest version on [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore).
{% /step %}

{% step title="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:

```java
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>: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'
```

**Method 2: Manual Configuration**

{% codetabs %}
```groovy Gradle
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
}
```

```xml Maven
<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>
```
{% /codetabs %}

Replace `YOUR-OS-ARCHITECTURE` with one of the supported combinations from the Supported OS and Architecture Combinations section.
{% /step %}
{% /steps %}

{% callout type="warning" %}
**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`).
{% /callout %}
{% /step %}

{% step title="Initialize the SDK" %}
After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys).

{% callout type="warning" %}
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
{% /callout %}

An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK.

{% codetabs %}
```java Java
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 myStatsigServer = new Statsig(SECRET_KEY, options);
myStatsigServer.initialize().get();
```

```kotlin Kotlin
import com.statsig.*

// All StatsigOptions are optional, feel free to adjust them as needed
val options = StatsigOptions.Builder()
    .setSpecsSyncIntervalMs(10000)
    .setEventLoggingFlushIntervalMs(10000)
    .setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
    .build()

val myStatsigServer = Statsig(SECRET_KEY, options)
myStatsigServer.initialize().get()
```
{% /codetabs %}

`initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls.
{% /step %}
{% /steps %}

## Getting started

### Quick start example

{% steps %}
{% step title="Create a new Java project" %}
Create a new Gradle or Maven project with the following structure:

```
my-statsig-app/
├── build.gradle (or pom.xml)
└── src/main/java/ExampleApp.java
```
{% /step %}

{% step title="Add Statsig dependency" %}
{% codetabs %}
```groovy build.gradle
plugins {
    id 'java'
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.statsig:javacore:X.X.X:uber'
}

application {
    mainClass = 'ExampleApp'
}
```

```xml pom.xml
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-statsig-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <dependency>
            <groupId>com.statsig</groupId>
            <artifactId>javacore</artifactId>
            <version>X.X.X</version>
            <classifier>uber</classifier>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <mainClass>ExampleApp</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```
{% /codetabs %}

Replace `X.X.X` with the latest version from [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore).
{% /step %}

{% step title="Write your application code" %}
{% codetabs %}
```java 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("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();
        }
    }
}
```

```kotlin ExampleApp.kt
import com.statsig.*

fun main() {
    // Initialize Statsig
    val options = StatsigOptions.Builder().build()
    val statsig = Statsig("YOUR_SERVER_SECRET_KEY", options)
    statsig.initialize().get()
    
    try {
        // Check a feature gate
        val isEnabled = statsig.checkGate("user123", "my_feature_gate")
        println("Feature gate is ${if (isEnabled) "enabled" else "disabled"}")
        
        // Get a config
        val config = statsig.getConfig("user123", "my_config")
        println("Config value: ${config.getString("some_parameter", "default_value")}")
    } finally {
        // Always shutdown Statsig when done
        statsig.shutdown().get()
    }
}
```
{% /codetabs %}

Replace `YOUR_SERVER_SECRET_KEY` with your actual server secret key from the [Statsig Console](https://console.statsig.com/).
{% /step %}

{% step title="Run the application" %}
{% codetabs %}
```bash Gradle
./gradlew run
```

```bash Maven
mvn compile exec:java
```
{% /codetabs %}

If everything is set up correctly, you should see output related to your feature gate and configuration.
{% /step %}
{% /steps %}

## Working with the SDK

### Checking a Feature Flag/Gate

After the SDK is initialized, you can fetch a [**Feature Gate**](/feature-flags/overview). 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](#statsig-user)). To check a gate for a user:

{% codetabs %}
```java Java
String userID = "user_id";
boolean result = statsig.checkGate(userID, "my_feature_gate");

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
boolean gateResult = statsig.checkGate(user, "my_feature_gate");
```

```kotlin Kotlin
val userID = "user_id"
val result = statsig.checkGate(userID, "my_feature_gate")

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
val gateResult = statsig.checkGate(user, "my_feature_gate")
```
{% /codetabs %}

### 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**](/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example:

{% codetabs %}
```java Java
String userID = "user_id";
DynamicConfig config = statsig.getConfig(userID, "my_config");

String name = config.getString("name", "");
int size = config.getInt("size", 10);

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
DynamicConfig dynamicConfig = statsig.getConfig(user, "my_config");
```

```kotlin Kotlin
val userID = "user_id"
val config = statsig.getConfig(userID, "my_config")

val name = config.getString("name", "")
val size = config.getInt("size", 10)

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
val dynamicConfig = statsig.getConfig(user, "my_config")
```
{% /codetabs %}

### Getting a Layer/Experiment

**Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but [layers](/experiments/layers-overview) are recommended because layers make parameters reusable and support mutually exclusive experiments.

{% codetabs %}
```java Java
String userID = "user_id";

// Getting an Experiment
Experiment experiment = statsig.getExperiment(userID, "my_experiment");
String expName = experiment.getString("experiment_param", "");

// Getting a Layer
Layer layer = statsig.getLayer(userID, "my_layer");
String layerValue = layer.getString("layer_param", "default");

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
    
Experiment experimentWithUser = statsig.getExperiment(user, "my_experiment");
Layer layerWithUser = statsig.getLayer(user, "my_layer");
```

```kotlin Kotlin
val userID = "user_id"

// Getting an Experiment
val experiment = statsig.getExperiment(userID, "my_experiment")
val expName = experiment.getString("experiment_param", "")

// Getting a Layer
val layer = statsig.getLayer(userID, "my_layer")
val layerValue = layer.getString("layer_param", "default")

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
    
val experimentWithUser = statsig.getExperiment(user, "my_experiment")
val layerWithUser = statsig.getLayer(user, "my_layer")
```
{% /codetabs %}

### Retrieving Feature Gate Metadata

To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object:

{% codetabs %}
```java Java
String userID = "user_id";
FeatureGate gate = statsig.getFeatureGate(userID, "my_feature_gate");

System.out.println("Gate name: " + gate.name);
System.out.println("Gate value: " + gate.value);
System.out.println("Rule ID: " + gate.ruleID);

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
FeatureGate gateWithUser = statsig.getFeatureGate(user, "my_feature_gate");
```

```kotlin Kotlin
val userID = "user_id"
val gate = statsig.getFeatureGate(userID, "my_feature_gate")

println("Gate name: ${gate.name}")
println("Gate value: ${gate.value}")
println("Rule ID: ${gate.ruleID}")

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
val gateWithUser = statsig.getFeatureGate(user, "my_feature_gate")
```
{% /codetabs %}

### Parameter stores

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.

{% codetabs %}
```java Java
String userID = "user_id";
ParameterStore store = statsig.getParameterStore(userID, "my_param_store");

String stringValue = store.getString("string_param", "default");
int intValue = store.getInt("int_param", 0);
boolean boolValue = store.getBoolean("bool_param", false);
double doubleValue = store.getDouble("double_param", 0.0);

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
ParameterStore storeWithUser = statsig.getParameterStore(user, "my_param_store");
```

```kotlin Kotlin
val userID = "user_id"
val store = statsig.getParameterStore(userID, "my_param_store")

val stringValue = store.getString("string_param", "default")
val intValue = store.getInt("int_param", 0)
val boolValue = store.getBoolean("bool_param", false)
val doubleValue = store.getDouble("double_param", 0.0)

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
val storeWithUser = statsig.getParameterStore(user, "my_param_store")
```
{% /codetabs %}

### Logging an Event

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:

{% codetabs %}
```java Java
import java.util.HashMap;
import java.util.Map;

String userID = "user_id";
String eventName = "my_custom_event";

// Simple event
statsig.logEvent(userID, eventName);

// Event with value
statsig.logEvent(userID, eventName, 10.5);

// Event with metadata
Map<String, String> metadata = new HashMap<>();
metadata.put("key1", "value1");
metadata.put("key2", "value2");
statsig.logEvent(userID, eventName, metadata);

// Event with value and metadata
statsig.logEvent(userID, eventName, 10.5, metadata);

// with StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
statsig.logEvent(user, eventName, 10.5, metadata);
```

```kotlin Kotlin
val userID = "user_id"
val eventName = "my_custom_event"

// Simple event
statsig.logEvent(userID, eventName)

// Event with value
statsig.logEvent(userID, eventName, 10.5)

// Event with metadata
val metadata = mapOf(
    "key1" to "value1",
    "key2" to "value2"
)
statsig.logEvent(userID, eventName, metadata)

// Event with value and metadata
statsig.logEvent(userID, eventName, 10.5, metadata)

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
statsig.logEvent(user, eventName, 10.5, metadata)
```
{% /codetabs %}

### 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.

{% codetabs %}
```java Java
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 StatsigUser
StatsigUser user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build();
statsig.forwardLogLineEvent(user, payload);
```

```kotlin Kotlin
val userID = "user_id"

val payload = mapOf(
    "log_level" to "error",
    "message" to "Something went wrong",
    "timestamp" to System.currentTimeMillis()
)

statsig.forwardLogLineEvent(userID, payload)

// with StatsigUser
val user = StatsigUser.builder()
    .userID("user_id")
    .email("my_user@example.com")
    .build()
statsig.forwardLogLineEvent(user, payload)
```
{% /codetabs %}

## Using shared instance

To access a single Statsig instance globally throughout your codebase, use the shared instance singleton pattern:

{% codetabs %}
```java Java
import com.statsig.*;

// Create a shared instance that can be accessed globally
StatsigServer statsig = Statsig.newShared("secret-key");
statsig.initialize().get();

// Access the shared instance from anywhere in your code
StatsigServer sharedStatsig = Statsig.shared();
boolean isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name");

// Check if a shared instance exists
if (Statsig.hasSharedInstance()) {
  // Use the shared instance
}

// Remove the shared instance when no longer needed
Statsig.removeShared();
```

```kotlin Kotlin
import com.statsig.*

// Create a shared instance that can be accessed globally
val statsig = Statsig.newShared("secret-key")
statsig.initialize().get()

// Access the shared instance from anywhere in your code
val sharedStatsig = Statsig.shared()
val isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name")

// Check if a shared instance exists
if (Statsig.hasSharedInstance()) {
  // Use the shared instance
}

// Remove the shared instance when no longer needed
Statsig.removeShared()
```
{% /codetabs %}

* `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)

{% callout type="note" %}
`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.
{% /callout %}

## 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.

{% codetabs %}
```java Java
String userID = "user_id";

// Check gate without logging exposure
boolean result = statsig.checkGateWithExposureLoggingDisabled(userID, "my_feature_gate");

// Manually log the exposure when ready
statsig.manuallyLogGateExposure(userID, "my_feature_gate");

// Works with configs too
DynamicConfig config = statsig.getConfigWithExposureLoggingDisabled(userID, "my_config");
statsig.manuallyLogConfigExposure(userID, "my_config");

// And with experiments/layers
Experiment 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");
```

```kotlin Kotlin
val userID = "user_id"

// Check gate without logging exposure
val result = statsig.checkGateWithExposureLoggingDisabled(userID, "my_feature_gate")

// Manually log the exposure when ready
statsig.manuallyLogGateExposure(userID, "my_feature_gate")

// Works with configs too
val config = statsig.getConfigWithExposureLoggingDisabled(userID, "my_config")
statsig.manuallyLogConfigExposure(userID, "my_config")

// And with experiments/layers
val experiment = statsig.getExperimentWithExposureLoggingDisabled(userID, "my_experiment")
statsig.manuallyLogExperimentExposure(userID, "my_experiment")

val layer = statsig.getLayerWithExposureLoggingDisabled(userID, "my_layer")
statsig.manuallyLogLayerParameterExposure(userID, "my_layer", "parameter_name")
```
{% /codetabs %}

## 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](/sdks/user#why-is-an-id-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.

{% codetabs %}
```java Java
import com.statsig.*;
import java.util.HashMap;
import java.util.Map;

// Build a user with various fields
Map<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 evaluation
boolean result = statsig.checkGate(user, "my_feature_gate");
```

```kotlin Kotlin
import com.statsig.*

// Build a user with various fields
val customFields = mapOf(
    "plan" to "premium",
    "age" to 25
)

val privateAttributes = mapOf(
    "internal_id" to "123456"
)

val 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 evaluation
val result = statsig.checkGate(user, "my_feature_gate")
```
{% /codetabs %}

## 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.

{% codetabs %}
```java Java
Map<String, String> privateAttributes = new HashMap<>();
privateAttributes.put("sensitive_field", "sensitive_value");

StatsigUser user = StatsigUser.builder()
    .userID("user_123")
    .privateAttributes(privateAttributes)
    .build();
```

```kotlin Kotlin
val privateAttributes = mapOf(
    "sensitive_field" to "sensitive_value"
)

val user = StatsigUser.builder()
    .userID("user_123")
    .privateAttributes(privateAttributes)
    .build()
```
{% /codetabs %}

## Statsig Options

You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client.

{% accordion title="StatsigOptions" %}
{% parameter name="environment" type="string" %}
Environment parameter for evaluation.
{% /parameter %}

{% parameter name="specsUrl" type="string" %}
Custom URL for fetching feature specifications.
{% /parameter %}

{% parameter name="specsSyncIntervalMs" type="long" %}
How often the SDK updates specifications from Statsig servers (in milliseconds).
{% /parameter %}

{% parameter name="fallbackToStatsig" type="boolean" %}
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.
{% /parameter %}

{% parameter name="logEventUrl" type="string" %}
Custom URL for logging events.
{% /parameter %}

{% parameter name="disableAllLogging" type="boolean" %}
If true, the SDK doesn't collect any logging within the session, including custom events and config check exposure events.
{% /parameter %}

{% parameter name="enableIDLists" type="boolean" %}
Required to be `true` when using segments with more than 1000 IDs.
{% /parameter %}

{% parameter name="disableUserAgentParsing" type="boolean" %}
If true, the SDK doesn't parse User-Agent strings into `browserName`, `browserVersion`, `systemName`, `systemVersion`, and `appVersion` when needed for evaluation.
{% /parameter %}

{% parameter name="disableUserCountryLookup" type="boolean" %}
If true, the SDK doesn't parse IP addresses (from `user.ip`) into country codes when needed for evaluation.
{% /parameter %}

{% parameter name="eventLoggingFlushIntervalMs" type="long" %}
How often events are flushed to Statsig servers (in milliseconds).
{% /parameter %}

{% parameter name="eventLoggingMaxQueueSize" type="int" %}
Maximum number of events to queue before forcing a flush.
{% /parameter %}

{% parameter name="dataStore" type="DataStore" %}
An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network.
{% /parameter %}

{% parameter name="proxyConfig" type="ProxyConfig" %}
Configuration for connecting through an outbound HTTP proxy.
{% /parameter %}

{% parameter name="specAdapterConfigs" type="List<SpecAdapterConfig>" %}
Advanced configuration for fetching specs from multiple sources or protocols, including [Statsig Forward Proxy](/infrastructure/api_proxy/introduction) over gRPC websocket streaming.

Each `SpecAdapterConfig` can set:

* `adapterType`: one of `SpecAdapterType.DATA_STORE`, `SpecAdapterType.NETWORK_HTTP`, or `SpecAdapterType.NETWORK_GRPC_WEBSOCKET`
* `specsUrl`: optional endpoint override for the adapter
* `initTimeoutMs`: optional initialization timeout in milliseconds
* `authenticationMode`: optional transport auth mode via `AuthenticationMode.NONE`, `AuthenticationMode.TLS`, or `AuthenticationMode.MTLS`
* `caCertPath`, `clientCertPath`, `clientKeyPath`, `domainName`: optional TLS and mTLS fields for gRPC websocket connections
{% /parameter %}

{% parameter name="persistentStorage" type="PersistentStorage" %}
Interface to use persistent storage within the SDK.
{% /parameter %}

{% parameter name="outputLoggerLevel" type="OutputLogger.LogLevel" %}
Set the logging level for the SDK. Options: `NONE`, `ERROR`, `WARN`, `INFO`, `DEBUG`.
{% /parameter %}

{% parameter name="observabilityClient" type="ObservabilityClient" %}
Interface to integrate observability metrics exposed by the SDK.
{% /parameter %}

***

{% codetabs %}
```java Java
// Example usage
StatsigOptions options = new StatsigOptions.Builder()
    .setEnvironment("staging")
    .setSpecsSyncIntervalMs(10000)
    .setEventLoggingFlushIntervalMs(5000)
    .setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
    .build();

Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get();
```

```kotlin Kotlin
// Example usage
val options = StatsigOptions.Builder()
    .setEnvironment("staging")
    .setSpecsSyncIntervalMs(10000)
    .setEventLoggingFlushIntervalMs(5000)
    .setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
    .build()

val statsig = Statsig("secret-key", options)
statsig.initialize().get()
```
{% /codetabs %}
{% /accordion %}

### 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](/infrastructure/api_proxy/introduction).

```java
ProxyConfig proxyConfig = new ProxyConfig();
proxyConfig.setProxyHost("proxy.example.com");
proxyConfig.setProxyPort(8080);
proxyConfig.setProxyProtocol("https");
proxyConfig.setCaCertPath("/etc/ssl/certs/corporate-ca.pem"); // Optional

StatsigOptions 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:

{% codetabs %}
```java Java
// Shutdown flushes all pending events and stops background tasks
statsig.shutdown();

// Or with a timeout (blocks until shutdown completes or timeout)
statsig.shutdown().get(5, TimeUnit.SECONDS);
```

```kotlin Kotlin
// Shutdown flushes all pending events and stops background tasks
statsig.shutdown()

// Or with a timeout (blocks until shutdown completes or timeout)
statsig.shutdown().get(5, TimeUnit.SECONDS)
```
{% /codetabs %}

## 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.

{% codetabs %}
```java Java
import java.util.HashMap;
import java.util.Map;

// Override a gate
statsig.overrideGate("my_feature_gate", true);

// Override a config
Map<String, Object> configOverride = new HashMap<>();
configOverride.put("key", "value");
configOverride.put("number", 42);
statsig.overrideConfig("my_config", configOverride);

// Override an experiment
Map<String, Object> experimentOverride = new HashMap<>();
experimentOverride.put("variant", "test");
statsig.overrideExperiment("my_experiment", experimentOverride);

// Override an experiment to a particular groupname
statsig.overrideExperimentByGroupName("my_experiment", "a_group_name");
statsig.overrideExperimentByGroupName("my_experiment", "a_group_name", "user_123");

// Override a layer
Map<String, Object> layerOverride = new HashMap<>();
layerOverride.put("layer_param", "override_value");
statsig.overrideLayer("my_layer", layerOverride);

// Clear all overrides
statsig.clearAllOverrides();

// Clear specific override
statsig.clearGateOverride("my_feature_gate");
statsig.clearConfigOverride("my_config");
```

```kotlin Kotlin
// Override a gate
statsig.overrideGate("my_feature_gate", true)

// Override a config
val configOverride = mapOf(
    "key" to "value",
    "number" to 42
)
statsig.overrideConfig("my_config", configOverride)

// Override an experiment
val experimentOverride = mapOf(
    "variant" to "test"
)
statsig.overrideExperiment("my_experiment", experimentOverride)

// Override an experiment to a particular groupname
statsig.overrideExperimentByGroupName("my_experiment", "a_group_name")
statsig.overrideExperimentByGroupName("my_experiment", "a_group_name", "user_123")

// Override a layer
val layerOverride = mapOf(
    "layer_param" to "override_value"
)
statsig.overrideLayer("my_layer", layerOverride)

// Clear all overrides
statsig.clearAllOverrides()

// Clear specific override
statsig.clearGateOverride("my_feature_gate")
statsig.clearConfigOverride("my_config")
```
{% /codetabs %}

## 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.

{% codetabs %}
```java Java
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 storage
StatsigOptions options = new StatsigOptions.Builder()
    .setPersistentStorage(new MyPersistentStorage())
    .build();

Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get();
```

```kotlin Kotlin
import com.statsig.*

class MyPersistentStorage : PersistentStorage {
    private val storage = mutableMapOf<String, MutableMap<String, StickyValues>>()

    override fun load(key: String): Map<String, StickyValues>? {
        // Load persisted sticky values for the given key
        // Key format is "{userId}:userID" or "{customId}:{idType}"
        return storage[key]
    }

    override fun save(key: String, configName: String, data: StickyValues) {
        // Save sticky values for a specific experiment/config
        storage.getOrPut(key) { mutableMapOf() }[configName] = data
    }

    override fun delete(key: String, configName: String) {
        // Delete sticky values for a specific experiment/config
        storage[key]?.remove(configName)
    }
}

// Use persistent storage
val options = StatsigOptions.Builder()
    .setPersistentStorage(MyPersistentStorage())
    .build()

val statsig = Statsig("secret-key", options)
statsig.initialize().get()
```
{% /codetabs %}

### 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 method
Map<String, StickyValues> values = persistentStorage.getValuesForUser(user, "userID");

// Generate a storage key from a user and ID type
String 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.
{% codetabs %}
```java Java
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 store
StatsigOptions options = new StatsigOptions.Builder()
    .setDataStore(new MyDataStore())
    .build();

Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get();
```

```kotlin Kotlin
import com.statsig.*
import java.util.concurrent.CompletableFuture

class MyDataStore : DataStore {
    override fun getDataSync(key: String): String? {
        // Synchronously fetch data for the given key
        // This is called during SDK evaluation
        return null
    }

    override fun setData(key: String, data: String): CompletableFuture<Void> {
        // Store data for the given key
        // Called when SDK receives updates from Statsig
        return CompletableFuture.completedFuture(null)
    }

    override fun initialize(): CompletableFuture<Void> {
        // Perform any initialization needed for your data store
        return CompletableFuture.completedFuture(null)
    }

    override fun shutdown() {
        // Clean up resources
    }
}

// Use data store
val options = StatsigOptions.Builder()
    .setDataStore(MyDataStore())
    .build()

val statsig = Statsig("secret-key", options)
statsig.initialize().get()
```
{% /codetabs %}

## 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.

{% codetabs %}
```java Java
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 logger
StatsigOptions options = new StatsigOptions.Builder()
    .setOutputLogger(new MyOutputLogger())
    .setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
    .build();

Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get();
```

```kotlin Kotlin
import com.statsig.*

class MyOutputLogger : OutputLogger {
    override fun log(level: OutputLogger.LogLevel, message: String) {
        // Route SDK logs to your logging system
        when (level) {
            OutputLogger.LogLevel.ERROR -> println("[ERROR] $message")
            OutputLogger.LogLevel.WARN -> println("[WARN] $message")
            OutputLogger.LogLevel.INFO -> println("[INFO] $message")
            OutputLogger.LogLevel.DEBUG -> println("[DEBUG] $message")
            else -> {}
        }
    }
}

// Use custom output logger
val options = StatsigOptions.Builder()
    .setOutputLogger(MyOutputLogger())
    .setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
    .build()

val statsig = Statsig("secret-key", options)
statsig.initialize().get()
```
{% /codetabs %}

## 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](/infrastructure/sdk-monitoring).

{% codetabs %}
```java Java
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 client
StatsigOptions options = new StatsigOptions.Builder()
    .setObservabilityClient(new MyObservabilityClient())
    .build();

Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get();
```

```kotlin Kotlin
import com.statsig.*

class MyObservabilityClient : ObservabilityClient {
    override fun emitMetric(metricName: String, value: Double, tags: Map<String, String>) {
        // Send metric to your monitoring system
        println("Metric: $metricName = $value, tags: $tags")
    }

    override fun startTimer(operationName: String) {
        // Start timing an operation
    }

    override fun endTimer(operationName: String, tags: Map<String, String>) {
        // End timing and emit duration metric
    }
}

// Use observability client
val options = StatsigOptions.Builder()
    .setObservabilityClient(MyObservabilityClient())
    .build()

val statsig = Statsig("secret-key", options)
statsig.initialize().get()
```
{% /codetabs %}

## FAQ

{% accordion-group %}
{% accordion title="What Java versions are supported?" %}
The Java Core SDK supports Java 8 and higher. Java 8 support was added in version 0.4.3.
{% /accordion %}

{% accordion title="Which platforms are supported?" %}
The SDK supports:

* Linux (x86\_64, arm64, musl variants)
* macOS (x86\_64, arm64)
* Windows (x86\_64)

Refer to the Tested Platforms section for verified Docker images.
{% /accordion %}

{% accordion title="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.
{% /accordion %}

{% accordion title="How do I use this with Alpine Linux?" %}
For Alpine Linux (musl-based systems), install compatibility packages:

```dockerfile
RUN apk add --no-cache libgcc gcompat
```

The SDK will automatically use musl-compatible native libraries.
{% /accordion %}

{% accordion title="How do I handle initialization in production?" %}
The SDK initialization is asynchronous. Use `.get()` on the CompletableFuture to wait for initialization:

```java
Statsig statsig = new Statsig("secret-key", options);
statsig.initialize().get(); // Blocks until initialized
```

Always call `shutdown()` when your application terminates to flush pending events.
{% /accordion %}

{% accordion title="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.
{% /accordion %}

{% accordion title="How do I debug SDK issues?" %}
Set the output logger level to DEBUG to see detailed logs:

```java
StatsigOptions options = new StatsigOptions.Builder()
    .setOutputLoggerLevel(OutputLogger.LogLevel.DEBUG)
    .build();
```
{% /accordion %}
{% /accordion-group %}

## 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)

{% callout type="info" %}
This is available for Enterprise contracts. Reach out to our support team, your sales contact, or through our [Slack community](https://statsig.com/slack) to enable it.
{% /callout %}

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 evaluation
List<String> getFieldsNeededForGate(String gateName)

// Get user fields needed for a dynamic config evaluation
List<String> getFieldsNeededForDynamicConfig(String configName)

// Get user fields needed for an experiment evaluation
List<String> getFieldsNeededForExperiment(String experimentName)

// Get user fields needed for a layer evaluation
List<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 names
userID -> "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"
```
