• HOME
  • INTEGRATIONS
  • SDKS
  • GUIDES
  • API DOCS
No results for ""
EXPAND ALL
CLOSE
launchdarkly.com

EDIT ON GITHUB

Java SDK reference

Read time: 8 minutes
Last edited: Jul 02, 2020

This reference guide documents all of the methods available in our Java SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read Java SDK GitHub repository or our Javadocs. Additionally you can clone and run a sample application using this SDK and an example of running it in another JRE-based language such as Scala.

Android support

The Java SDK is intended for use in server environments only, and should not be used in mobile devices. Learn more about our client-side and server-side SDKs. If you want to use LaunchDarkly in an Android application, read the Android SDK reference.

Java compatibility
Version 5.0 and higher of the LaunchDarkly Java SDK is compatible with Java 8 and higher. Prior to version 5.0, the LaunchDarkly Java SDK also supported Java 7.

Getting started

Building on top of our Getting Started guide guide, the following steps will get you started with using the LaunchDarkly SDK in your Java application.

The first step is to install the LaunchDarkly SDK as a dependency in your application using your application's dependency manager. Refer to the SDK releases page to identify the latest version. In this example, it will use version 5.0.

1<dependency>
2 <groupId>com.launchdarkly</groupId>
3 <artifactId>launchdarkly-java-server-sdk</artifactId>
4 <version>5.0</version>
5</dependency>

Next you should import the LaunchDarkly client in your application code.

1import com.launchdarkly.sdk.*;
2import com.launchdarkly.sdk.server.*;

Once the SDK is installed and imported, you'll want to create a single, shared instance of LDClient. You should specify your SDK key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

1LDClient ldClient = new LDClient("YOUR_SDK_KEY");
LDClient must be a singleton

It's important to make this a singleton. Internally, the client instance maintains internal state that allows us to serve feature flags without making any remote requests. Be sure that you're not instantiating a new client with every request.

Using ldClient, you can check which variation a particular user should receive for a given feature flag.

1LDUser user = new LDUser("user@test.com");
2boolean showFeature = ldClient.boolVariation("your.feature.key", user, false);
3if (showFeature) {
4 // application code to show the feature
5}
6else {
7 // the code to run if the feature is off
8}

Lastly, when your application is about to terminate, shut down ldClient with close(). This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

1// shut down the client, since we're about to quit
2ldClient.close();

Customizing your client

You can also pass custom parameters to the client by creating a custom configuration object:

1LDConfig config = new LDConfig.Builder()
2 .http(
3 Components.httpConfiguration()
4 .connectTimeout(Duration.ofSeconds(3))
5 .socketTimeout(Duration.ofSeconds(3))
6 )
7 .events(
8 Components.sendEvents()
9 .flushInterval(Duration.ofSeconds(10))
10 )
11 .build();
12LDClient ldClient = new LDClient("YOUR_SDK_KEY", config);

Here, we've customized two properties for HTTP (the connect and socket timeouts), and one property for analytics events (the event flush interval).

To get a complete list of configuration options for the client, including proxy settings, timeouts, and streaming/polling options, read the Javadoc for LDConfig.Builder. You can also read the 4.x version).

Users

Feature flag targeting and rollouts are all determined by the user you pass to your variation calls. In our Java SDK, we use a builder pattern to make it easy to construct users. Here's an example:

1LDUser user = new LDUser.Builder("aa0ceb")
2 .firstName("Ernestina")
3 .lastName("Evans")
4 .email("ernestina@example.com")
5 .custom("groups",
6 LDValue.buildArray().add("Google").add("Microsoft").build())
7 .build()

Let's walk through this snippet. The first argument to the builder is the user's key. In this case we've used the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

Our Javadoc for LDUser.Builder shows you all the attributes that LaunchDarkly supports by default. In addition to these, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types

Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers. If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The Java SDK is strongly typed, so be aware of this distinction.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, and account plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the Java SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the Java SDK there are two ways to define private attributes for the entire LaunchDarkly client:

  • When creating the LDConfig object, you can call the allAttributesPrivate method, which takes in a boolean parameter. If true, all user attributes (except the key) for all users are removed before the user is sent to LaunchDarkly.
  • When creating the LDConfig object, you can call the privateAttributes method, which takes in a set of custom or built-in attributes as a parameter. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.
1LDConfig configWithAllAttributesPrivate = new LDConfig.Builder()
2 .events(
3 Components.sendEvents()
4 .allAttributesPrivate(true)
5 )
6 .build();
7
8LDConfig configWithSpecificAttributesPrivate = new LDConfig.Builder()
9 .events(
10 Components.sendEvents()
11 .privateAttributes(UserAttribute.NAME, UserAttribute.EMAIL,
12 UserAttribute.forName("someCustomAttribute"))
13 )
14 .build();

You can also mark attributes as private when building the user object itself by calling the equivalent “private” user builder method. For example:

1LDUser user = new LDUser.Builder("aa0ceb")
2 .privateEmail("test@example.com")
3 .build();

When this user is sent back to LaunchDarkly, the email attribute will be omitted.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1LDUser user = new LDUser.Builder("aa0ceb")
2 .anonymous(true)
3 .build();

You will still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this. Each unique user key registers a user in our system, so capture and reuse your anonymous user's key between requests.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing, because it keeps anonymous users from polluting your Users page!

Variation

The variation methods determine which variation of a feature flag a user receives. In Java, there is a variation method for each type: boolVariation, intVariation, doubleVariation, stringVariation (and jsonValueVariation, which can be of any JSON type).

1boolean value = ldClient.boolVariation("your.feature.key", user, false);

The variation methods take the feature flag key, an LDUser, and a default value.

The default value will only be returned if an error is encountered. For example, the default value returns if the feature flag key doesn't exist or the user doesn't have a key specified.

The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of time (but if you do need to, take a look at Identify).

VariationDetail

The variationDetail methods (boolVariationDetail, etc.) work the same as variation, but also provide additional "reason" information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the "reason" data programmatically; you can also view it with data export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.

Track

The track method allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

1ldClient.track("your-goal-key", user);

You can also attach custom JSON data to your event using an alternate version of track, trackData. This example sets the data to a JSON object, {"price": 320}, but it can be any value that can be represented in JSON; see LDValue.

1LDValue data = LDValue.buildObject().put("price", 320).build();
2ldClient.trackData("completed-purchase", user, data);

Or, if you are using experimentation, you can specify a numeric metric with trackMetric:

1double metricValue = 2.5;
2ldClient.trackMetric("page-load-time", user, LDValue.ofNull(), metricValue);

Identify

The identify method creates or updates users in LaunchDarkly, making them available for targeting and autocomplete on the dashboard. In most cases, you won't need to call identify. The variation call will automatically create users on the dashboard for you. Identify can be useful if you want to pre-populate your dashboard before launching any features.

1ldClient.identify(user);

All flags

Creating users

Unlike variation and identify calls, allFlagsState does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.

The allFlagsState method captures the state of all feature flags with regard to a specific user. This includes their values as well as other metadata.

This method can be useful for passing feature flags to your front-end. In particular, it can be used to provide bootstrap flag settings for our JavaScript SDK.

1FeatureFlagsState state = ldClient.allFlagsState(user);

Secure mode hash

The secureModeHash method computes an HMAC signature of a user signed with the client's SDK key. If you're using our JavaScript SDK for client-side flags, this method generates the signature you need for secure mode.

1ldClient.secureModeHash(user);

Flush

Internally, the LaunchDarkly SDK keeps an event buffer for track and identify calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a REPL), you may want to manually call flush to process events immediately.

1ldClient.flush();

The flush interval is configurable. If you need to change the interval, you can do so via LDConfig.Builder and Components.sendEvents().

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise. You can do this by setting offline mode in the client's LDConfig.

1LDConfig config = new LDConfig.Builder()
2 .offline(true)
3 .build();
4LDClient ldClient = new LDClient("YOUR_SDK_KEY", config);
5ldClient.boolVariation("any.feature.flag", user, false)
6
7// This call to ldClient.boolVariation always
8// returns the default value (false)

Close

Close safely shuts down the client instance and releases all resources associated with the client. In most long-running applications, you should not have to call close.

1ldClient.close()

Logging

The Java SDK uses SLF4J. All loggers are namespaced under com.launchdarkly. For an example configuration check out the hello-java project.

You can filter by logger name. Here are available logger names, starting with version 5.0:

  • com.launchdarkly.sdk.server.LDClient: general messages that do not fall into any other categories
  • com.launchdarkly.sdk.server.LDClient.DataSource: messages related to how the SDK obtains feature flag data-- normally this means messages about the streaming connection to LaunchDarkly, but if you use polling mode or file data instead, those will be logged under this name too
  • com.launchdarkly.sdk.server.LDClient.DataStore: messages related to how feature flag data is stored-- for instance, database errors if you are using a database integration
  • com.launchdarkly.sdk.server.LDClient.Evaluation: messages related to feature flag evaluation
  • com.launchdarkly.sdk.server.LDClient.Events: messages related to analytics event processing

In versions of the SDK before 5.0, logger names were not standardized and were sometimes the names of Java classes that are not part of the public API, but they consistently had a package prefix of either com.launchdarkly.client. or com.launchdarkly.eventsource.

For an example SLF4J configuration, check out the hello-java project.

Be aware of two considerations when enabling the DEBUG log level:

  1. Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
  2. Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.

Database integrations

The Java SDK can use Redis, Consul, or DynamoDB as a persistent store of feature flag configurations.

To learn more, read Using a persistent feature store.

Using the Java SDK in OSGi

Versions 4.6.0 and higher of the SDK can be installed as OSGi bundles.

Note that the SDK's default jar—the one you get from Maven or Gradle if you do not specify a "classifier"—does not contain Gson or SLF4j, since applications are often built with their own specific versions of those libraries. Therefore, using that jar in OSGi requires Gson and SLF4j to be provided by some other bundle.

However, there is also a distribution that includes Gson and SLF4j as part of the SDK bundle. You can use this if you do not care about controlling the versions of those libraries separately. To do so, add the classifier "all":

1<!-- in Maven: -->
2<dependency>
3 <groupId>com.launchdarkly</groupId>
4 <artifactId>launchdarkly-java-server-sdk</artifactId>
5 <version>5.0.0</version>
6 <classifier>all</classifier>
7</dependency>
8
9// or in Gradle:
10"com.launchdarkly:launchdarkly-java-server-sdk:5.0.0:all"
Potential network connectivity issues caused by DNS caching

There is a potential problem for any Java application that communicates with a web service, if that service uses a load-balancing framework. LaunchDarkly is such a service. The issue is that if a service starts to use a different set of IP addresses, a Java application could continue trying to use an old IP address, causing connection attempts to fail. In most environments, this is unlikely to be a problem because IP addresses are not cached for very long.

However, Java has special behavior if the runtime environment has a security manager: in that case, it caches IP addresses indefinitely and will never update them until the application is restarted. If you are running in an environment that has a security manager—or if you're not sure whether that is the case—we recommend that you set the cache duration (TTL) explicitly. This page describes two ways to do so.