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-- head to our Java SDK GitHub repository or our Javadocs to look under the hood.
Our Java SDK is intended for use in server environments only, and should not be used in mobile devices.
If you want to use LaunchDarkly in an Android application, see our Android SDK Reference Guide.
The LaunchDarkly Java SDK is compatible with Java 7 and higher.
If you haven't taken a look at our Quickstart guide yet, we recommend starting there to see how install our SDK into your Java application.
Once the SDK is installed, you'll want to create a single, shared instance of
LDClient 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.
You can also pass custom parameters to the client by creating a custom configuration object:
LDConfig config = new LDConfig.Builder() .connectTimeout(3) .socketTimeout(3) .build(); LDClient ldClient = new LDClient("YOUR_SDK_KEY", config);
Here, we've customized the client connect and socket timeout parameters. See the Javadoc for LDConfig.Builder for the complete list of configuration options for the client including proxy settings, timeouts, and more.
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:
LDUser user = new LDUser.Builder("aa0ceb") //Required .firstName("Ernestina") //Optional .lastName("Evans") //Optional .email("firstname.lastname@example.org") //Optional .custom("groups", Arrays.asList("Google", "Microsoft")) //Optional .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
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-- organizations, groups, account plans-- anything you pass to us becomes available instantly on our dashboard.
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
LDConfigobject, you can call the
allAttributesPrivatemethod, 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
LDConfigobject, you can call the
privateAttributeNamesmethod, 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.
You can also mark attributes as private when building the user object itself by calling the equivalent “private” user builder method. For example:
LDUser user = new LDUser.Builder("aa0ceb") .privateEmail("email@example.com") .build();
When this user is sent back to LaunchDarkly, the
You can also distinguish logged-in users from anonymous users in the SDK, as follows:
LDUser user = new LDUser.Builder("aa0ceb") .anonymous(true) .build();
You will still need to generate a unique key for anonymous users-- session IDs or UUIDs work best for this.
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-- it keeps anonymous users from polluting your Users page!
variation method determines which variation of a feature flag a user receives. In Java, there is a
variation method for each type (e.g.
boolean value = ldClient.boolVariation("your.feature.key", user, false);
variation calls 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, if the feature flag key doesn't exist or the user doesn't have a key specified.
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 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 in the analytics data stream, if you are capturing detailed analytics events for this flag.
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:
You can also attach custom JSON data to your event by passing an extra parameter to
JsonObject data = new JsonObject(); data.add("price", 320); ldClient.track("Completed purchase", user, data);
You can attach any JSON object (using Google's GSON API) to your events.
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
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.
Note that unlike variation and identify calls, allFlagsState does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.
allFlagsState captures the state of all feature flags with regard to a specific user. This includes their values as well as other metadata.
FeatureFlagsState state = ldClient.allFlagsState(user);
Internally, the LaunchDarkly SDK keeps an event buffer for
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.
Note that the flush interval is configurable-- if you need to change the interval, you can do so via
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 config = new LDConfig.Builder() .offline(true) .build(); LDClient ldClient = new LDClient("YOUR_SDK_KEY", config); ldClient.boolVariation("any.feature.flag", user, false) // will always return the default value (false)
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.
Be aware of two considerations when enabling the DEBUG log level:
- Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
- Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.
The Java SDK provides an interface to use Redis as a persistent store of feature flag configurations. Here's an example client configuration hooked up to a Redis instance:
String host = "localhost"; int port = 443; int cacheTimeSecs = 60 RedisFeatureStore store = new RedisFeatureStoreBuilder(host, port, cacheTimeSecs).build() LDConfig config = new LDConfig.Builder() .featureStore(store) .build(); LDClient ldClient = new LDClient("YOUR_SDK_KEY", config);
RedisFeatureStore configuration options, please see the SDK's JavaDoc