HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityLog In

Initialize SDK

This topic describes how to initialize the Optimizely Java SDK in your application.

Use the Optimizely Builder to initialize the Java SDK and instantiate an instance of the Optimizely client class that exposes API methods like Decide methods.

Version

SDK v3.2.0 and higher

Description

Some parameters are optional because the SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want to override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

The table below lists the optional builder methods.

Parameter

Description

withConfigManager(
ProjectConfigManager)

ProjectConfigManager object to manage project configuration. You should provide an instance of `HttpProjectConfigManage or your own custom object.

If this is not set, the static ProjectConfig will be used without polling datafile periodically.

withEventProcessor(
EventProcessor)

EventProcessor object to process events. You should provide an instance of BatchEventProcessor with AsyncEventHandler or your own custom object.
If this is not set, ForwardingEventProcessor will be used with NoopEventHandler() will be used by default.

withUserProfileService(
UserProfileService)

UserProfileService object to support persistent variation assignments.
If this is not set, persistent decisions are not supported.

withErrorHandler(ErrorHandler)

ErrorHandler object to handle errors.

withDatafile(String)

The JSON string representing the project.

If an instance of ProjectConfigManager is not provided, this datafile is needed to initialize the ProjectConfig statically.

withDefaultDecideOptions(
List)

Array of OptimizelyDecideOption enums. When the Optimizely client is constructed with this parameter, it sets default decide options which are applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not overrides defaults).
For example code, see OptimizelyDecideOption.

Returns

Instantiates an instance of the Optimzely class.

Example

The example below shows how to initialize the Optimizely SDK using the builder options.

Optimizely provides provides default implementations of HttpProjectConfigManager, BatchEventProcessor and AsyncEventHandler.

ProjectConfigManager configManager = HttpProjectConfigManager.builder()
    .withSdkKey(sdkKey)
    .withDatafile(datafile)
    .build();

EventHandler eventHandler = AsyncEventHandler.builder()
    .withQueueCapacity(20000)
    .withNumWorkers(1)
    .build();

EventProcessor batchProcessor = BatchEventProcessor.builder()
    .withBatchSize(50)
    .withEventHandler(eventHandler)
    .withFlushInterval(TimeUnit.MINUTES.toMillis(1))
    .build();

Optimizely optimizely = Optimizely.builder()
    .withConfigManager(configManager)
    .withEventProcessor(batchProcessor)
    .build();

Exceptions

Exception

Meaning

ConfigParseException

The datafile could not be parsed either because it is malformed or has an incorrect schema.

HttpProjectConfigManager

Whenever the experiment configuration changes, the SDK uses automatic datafile management (ADM) to handle the change for you.

HttpProjectConfigManager is an implementation of the abstract PollingProjectConfigManager. The poll method is extended and makes an HTTP GET request to the configured URL to asynchronously download the project datafile and initialize an instance of the ProjectConfig.

By default, HttpProjectConfigManager will block until the first successful datafile retrieval, up to a configurable timeout.
Set the frequency of the polling method and the blocking timeout with withPollingInterval() and withBlockingTimeout(), pulling the default values from global properties.

The example below shows how to initialize HttpProjectConfigManager with builder options.

ProjectConfigManager projectConfigManager = HttpProjectConfigManager.builder()
    .withSdkKey(sdkKey)
    .withDatafile(datafile)
    .withPollingInterval(1, TimeUnit.MINUTES)
    .withBlockingTimeout(10, TimeUnit.SECONDS)
    .build();

SDK key

The SDK key is used to compose the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval is used to specify a fixed delay between consecutive HTTP requests for the datafile.

Initial datafile

You can provide an initial datafile via the builder to bootstrap the ProjectConfigManager so that it can be used immediately without blocking execution. The initial datafile also serves as a fallback datafile if HTTP connection cannot be established. This is useful in mobile environments, where internet connectivity is not guaranteed.

The preceding datafile will be discarded after the first successful datafile poll.

Builder methods

The following builder methods can be used to customize the HttpProjectConfigManager con#figuration.

Method

Default value

Description

withDatafile(String)

null

Initial datafile, typically sourced from a local cached source

withUrl(String)

null

URL override location used to specify custom HTTP source for the Optimizely datafile

withFormat(String)

https://cdn.optimizely.com/datafiles/%s.json

Parameterized datafile URL by SDK key

withPollingInterval(Long, TimeUnit)

5 minutes

Fixed delay between fetches for the datafile

withBlockingTimeout(Long, TimeUnit)

10 seconds

Maximum time to wait for initial bootstrapping

withSdkKey(String)

null

Optimizely project SDK key; required unless source URL is overridden

Advanced configuration

The following properties can be set to override the default configuration for HttpProjectConfigManager.

Property

Default value

Description

http.project.config.manager.polling.duration

5

Fixed delay between fetches for the datafile

http.project.config.manager.polling.unit

MINUTES

Time unit corresponding to polling interval

http.project.config.manager.blocking.duration

10

Maximum time to wait for initial bootstrapping

http.project.config.manager.blocking.unit

SECONDS

Time unit corresponding to blocking duration

http.project.config.manager.sdk.key

null

Optimizely project SDK key

Update Config Notifications

A notification signal will be triggered whenever a new datafile is fetched. To subscribe to these notifications, use Optimizely.addUpdateConfigNotificationHandler:

NotificationHandler<UpdateConfigNotification> handler = message ->
    System.out.println("Received new datafile configuration");
optimizely.addUpdateConfigNotificationHandler(handler);

Alternatively, you can add the handler directly to the NotificationCenter:

notificationCenter.addNotificationHandler(UpdateConfigNotification.class, handler);

AsyncEventHandler

AsyncEventHandler provides an implementation of EventHandler backed by a ThreadPoolExecutor. Events triggered from the Optimizely SDK are queued immediately as discrete tasks to the executor and processed in the order they were submitted.

Each worker is responsible for making outbound HTTP requests to the Optimizely log endpoint for metrics tracking. Configure the default queue size and number of workers via global properties. Use AsyncEventHandler.Builder to override the default queue size and number of workers.

📘

Note

When using the Optimizely builder class, you must provide an implementation of the event handler as shown below. Otherwise, the Optimizely instance will default to a no-op event handler.

To use AsyncEventHandler, you must build an instance with AsyncEventHandler.Builder and pass the instance to the Optimizely.Builder.

Note that you can also initialize the SDK with the OptimizelyFactory methods if you want to use the default AsyncEventHandler implementation.

EventHandler eventHandler = AsyncEventHandler.builder()
    .withQueueCapacity(10000)
    .withNumWorkers(5)
    .build();

Queue capacity

You can set the queue capacity to initialize the backing queue for the executor service. If the queue fills up, events will be dropped and an exception will be logged. Setting a higher queue value will prevent event loss but will use more memory if the workers cannot keep up with the production rate.

Number of workers

The number of workers determines the number of threads the thread pool uses.

Builder methods

The following builder methods can be used to customize the AsyncEventHandler configuration.

Method

Default value

Description

withQueueCapacity(int)

1000

Queue size for pending logEvents

withNumWorkers(int)

2

Number of worker threads

withMaxTotalConnections(int)

200

Maximum number of connections

withMaxPerRoute(int)

20

Maximum number of connections per route

withValidateAfterInactivity(int)

5000

Time to maintain idol connections (in milliseconds)

Advanced configuration

The following properties can be set to override the default configuration for AsyncEventHandler.

Property

Default value

Description

async.event.handler.queue.capacity

10000

Queue size for pending logEvents

async.event.handler.num.workers

2

Number of worker threads

async.event.handler.max.connections

200

Maximum number of connections

async.event.handler.event.max.per.route

20

Maximum number of connections per route

async.event.handler.validate.after

5000

Time to maintain idol connections (in milliseconds)

BatchEventProcessor

The Optimizely SDK provides BatchEventProcessor, the default implementation of the EventProcessor interface and batches events.

You can find details and configuration options here.

EventHandler eventHandler = AsyncEventHandler.builder()
    .withQueueCapacity(10000)
    .withNumWorkers(5)
    .build();

EventProcessor batchProcessor = BatchEventProcessor.builder()
    .withBatchSize(50)
    .withEventHandler(eventHandler)
    .build();

Optimizely Properties

When an optimizely.properties file is available within the runtime classpath it can be used to provide default values of a given Optimizely resource. Refer to the resource implementation for available configuration parameters.

Here is an example optimizely.properties file:

http.project.config.manager.polling.duration = 1
http.project.config.manager.polling.unit = MINUTES

async.event.handler.queue.capacity = 20000
async.event.handler.num.workers = 5

OptimizelyFactory

In this package, OptimizelyFactory provides basic utility to instantiate the Optimizely SDK with a minimal number of configuration options. Configuration properties are sourced from Java system properties, environment variables, or an optimizely.properties file, in that order.

OptimizelyFactory does not capture all configuration and initialization options. For more use cases, build the resources via their respective builder classes.

When instantiated with the OptimizelyFactory methods, the Optimizely SDK will use the default configuration of HttpProjectConfigManager, BatchEventProcessor and AsyncEventHandler.

The example below shows how to initialize the Optimizely SDK using the OptimizelyFactory methods.

Optimizely optimizelyClient = OptimizelyFactory.newDefaultInstance(sdkKey);

// If you provide the SDK key via a global property, use the empty signature:
Optimizely optimizely = OptimizelyFactory.newDefaultInstance();

// with fallback datafile
Optimizely optimizelyClient = OptimizelyFactory.newDefaultInstance(sdkKey, datafile);

In addition to the datafile, you'll need to provide an event dispatcher (also called event handler) object as an argument to the Optimizely.builder function. Use our default event dispatcher implementation, or provide your own implementation as described in Configure the event dispatcher.

Use authenticated datafile in secure environment

📘

Beta feature

Contact your Customer Success Manager if you are interested in becoming an early user of authenticated datafiles as part of the beta secure environment feature.

You can fetch the Optimizely datafile from an authenticated endpoint using a server-side (only) Optimizely SDK. To use an authenticated datafile, download your Optimizely environment's access token from the Optimizely app at Settings>Environments. Select your secure environment, and copy the Datafile access token. The example below shows how to initialize the Optimizely client using an access token and sdkKey, enabling the client to fetch the authenticated datafile and complete initialization.

// fetch the datafile from an authenticated endpoint
String accessToken = "<YOUR_DATAFILE_ACCESS_TOKEN>";
String sdkKey = "<YOUR_SDK_KEY>";
Optimizely optimizelyClient = OptimizelyFactory.newDefaultInstance(sdkKey, null, accessToken);

Source files

The language/platform source files containing the implementation for Java are at Optimizely.java.


Did this page help you?