# Java Server SDK

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

- **Package:** `com.statsig:javacore` ([maven](https://search.maven.org/artifact/com.statsig/javacore))
- **Latest version:** 0.22.0
- **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-java)

> **Tip:**
>
> Migrating from the Legacy Java SDK? Refer to the [Migration Guide](https://docs.statsig.com/server-core/migration-guides/java).

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

   You can install the Statsig Java SDK 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.

   #### Gradle

   ```groovy
   repositories {
       mavenCentral()
   }

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

   #### Maven

   ```xml
   <dependencies>
       <dependency>
           <groupId>com.statsig</groupId>
           <artifactId>javacore</artifactId>
           <version>X.X.X</version>
           <classifier>uber</classifier>
       </dependency>
   </dependencies>
   ```

   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.

   1. **Install Core Library**

      #### Gradle

      ```groovy
      repositories {
          mavenCentral()
      }

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

      #### Maven

      ```xml
      <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](https://central.sonatype.com/artifact/com.statsig/javacore).
   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:

      ```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 receive output similar to:

      ```plaintext
      For Linux with arm64 architecture, add the following to build.gradle:
        implementation 'com.statsig:javacore:<version>:aarch64-unknown-linux-gnu'

      For Linux with x86_64 architecture, add the following to build.gradle:
        implementation 'com.statsig:javacore:<version>:x86_64-unknown-linux-gnu'
      ```

      **Method 2: Manual Configuration**

      #### Gradle

      ```groovy
      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
      }
      ```

      #### Maven

      ```xml
      <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.

   > **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 uses the appropriate musl-compatible native libraries (e.g., `x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`).
2. **Initialize the SDK**

   After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys).

   > **Warning:**
   >
   > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console.

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

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

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

## Getting started

### Quick start example

1. **Create a new Java project**

   Create a new Gradle or Maven project with the following structure:

   ```plaintext
   my-statsig-app/
   ├── build.gradle (or pom.xml)
   └── src/main/java/ExampleApp.java
   ```
2. **Add Statsig dependency**

   #### build.gradle

   ```groovy
   plugins {
       id 'java'
       id 'application'
   }

   repositories {
       mavenCentral()
   }

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

   application {
       mainClass = 'ExampleApp'
   }
   ```

   #### pom.xml

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

   Replace `X.X.X` with the latest version from [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore).
3. **Write your application code**

   #### ExampleApp.java

   ```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();
           }
       }
   }
   ```

   #### ExampleApp.kt

   ```kotlin
   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()
       }
   }
   ```

   Replace `YOUR_SERVER_SECRET_KEY` with your actual server secret key from the [Statsig Console](https://console.statsig.com/).
4. **Run the application**

   #### Gradle

   ```bash
   ./gradlew run
   ```

   #### Maven

   ```bash
   mvn compile exec:java
   ```

   If everything is set up correctly, you should see output related to your feature gate and configuration.

## Working with the SDK

### Checking a feature flag/gate

After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/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:

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

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

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

### Getting a layer/experiment

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

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

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

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

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

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

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

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

### Sending events to Log Explorer

You can forward logs to Logs Explorer for analysis using the Forward Log Line Event API. The API lets you include custom metadata and event values with each log.

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

## Using shared instance

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

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

- `Statsig.newShared(sdkKey, options)`: Creates a new shared instance of Statsig that you can access 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)

> **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 results in an error.

## Manual exposures

By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call `get()` on a layer parameter. To delay exposure logging until the user actually uses the feature, use manual exposures.

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

## 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. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks).

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 that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services.

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

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

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

## Statsig options

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

#### StatsigOptions

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| environment | string | No | — | Environment parameter for evaluation. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| specsUrl | string | No | — | Custom URL for fetching feature specifications. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| specsSyncIntervalMs | long | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| fallbackToStatsig | boolean | No | — | Turn this on if you're proxying `download_config_specs` / `get_id_lists` and want to fall back to the default Statsig endpoint to increase reliability. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventUrl | string | No | — | Custom URL for logging events. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableAllLogging | boolean | No | — | If true, the SDK doesn't collect any logging within the session, including custom events and config check exposure events. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| enableIDLists | boolean | No | — | Required to be `true` when using segments with more than 1000 IDs. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableUserAgentParsing | boolean | No | — | If true, the SDK doesn't parse User-Agent strings into `browserName`, `browserVersion`, `systemName`, `systemVersion`, and `appVersion` when needed for evaluation. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableUserCountryLookup | boolean | No | — | If true, the SDK doesn't parse IP addresses (from `user.ip`) into country codes when needed for evaluation. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| eventLoggingFlushIntervalMs | long | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| eventLoggingMaxQueueSize | int | No | — | Maximum number of events to queue before forcing a flush. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| dataStore | DataStore | No | — | An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| proxyConfig | ProxyConfig | No | — | Configuration for connecting through an outbound HTTP proxy. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| specAdapterConfigs | List<SpecAdapterConfig> | No | — | Advanced configuration for fetching specs from multiple sources or protocols, including [Statsig Forward Proxy](https://docs.statsig.com/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 using `AuthenticationMode.NONE`, `AuthenticationMode.TLS`, or `AuthenticationMode.MTLS` - `caCertPath`, `clientCertPath`, `clientKeyPath`, `domainName`: optional TLS and mTLS fields for gRPC websocket connections |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| persistentStorage | PersistentStorage | No | — | Interface to use persistent storage within the SDK. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| outputLoggerLevel | OutputLogger.LogLevel | No | — | Set the logging level for the SDK. Options: `NONE`, `ERROR`, `WARN`, `INFO`, `DEBUG`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| observabilityClient | ObservabilityClient | No | — | Interface to integrate observability metrics exposed by the SDK. |

---

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

### 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're routing spec downloads through [Statsig Forward Proxy](https://docs.statsig.com/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 the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before shutting down your app or server:

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

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

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

## 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. Persistent storage is useful for client-side A/B testing where you need users to always see the same variant.

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

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

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

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

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

## 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](https://docs.statsig.com/infrastructure/sdk-monitoring).

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

## FAQ

#### What Java versions are supported?

The Java Core SDK supports Java 8 and higher. Statsig added Java 8 support 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)

Refer to the Tested Platforms section for verified Docker images.

#### Should I use the uber JAR or platform-specific JARs?

Statsig recommends the uber JAR 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:

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

The SDK automatically uses 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:

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

Always call `shutdown()` when your application stops 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:

```java
StatsigOptions options = new StatsigOptions.Builder()
    .setOutputLoggerLevel(OutputLogger.LogLevel.DEBUG)
    .build();
```

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

> **Info:**
>
> This is available for Enterprise contracts. Reach out to the Statsig support team, your sales contact, or through the [Slack community](https://statsig.com/slack) to enable it.

These methods let you retrieve a list of user fields used in the targeting rules for gates, configs, experiments, and layers.

```java
// Get user fields needed for a gate 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"
```
