A/B Smartly - Java SDK
The A/B Smartly Java SDK provides both a blocking and an asynchronous interface. It is published as two artifacts with the same version and the same API, except for the types the asynchronous functions use:
| Artifact | Runs on | Asynchronous types |
|---|---|---|
com.absmartly.sdk:core-api |
Java 8 and later, Android API level 24+ | java.util.concurrent.CompletableFuture, java.util.function.* |
com.absmartly.sdk:core-api-java6 |
Java 6 and later, Android API level 19+ | the streamsupport backport: java8.util.concurrent.CompletableFuture, java8.util.function.* |
Use core-api unless you need Java 6 or 7, or Android below API level 24. Both artifacts provide the same com.absmartly.sdk classes, so depend on only one of them.
core-api has no restrictions on Java 24 and later.
With core-api-java6, the SDK runs on Java 24 and later, but the CompletableFuture backport's default async pool does not: it fails with NoClassDefFoundError: Could not initialize class java8.util.concurrent.TLR. The SDK never uses that pool. The futures the SDK returns, and the stages you chain on them with thenApply, thenCompose and the other instance methods, run *Async methods without an explicit executor on an SDK-owned pool of daemon threads, so context.waitUntilReadyAsync().thenApplyAsync(fn) is safe.
With core-api-java6, these cases still use the backport's default pool and must be given an executor on Java 24 and later:
- the static
CompletableFuture.supplyAsync(supplier)andCompletableFuture.runAsync(runnable)calls in your own code; - futures that you create yourself, including those returned by a custom
HTTPClient,ContextDataProviderorContextEventHandler, andABSmartly.getContextData()when a customContextDataProvideris configured; - futures derived through
minimalCompletionStage()or the staticCompletableFuture.allOfandanyOf, even when they start from an SDK future.
The A/B Smartly SDK is compatible with Android 4.4 and later (API level 19+). Use core-api on API level 24 and later, and core-api-java6 below API level 24.
The android.permission.INTERNET permission is required. To add this permission to your application ensure the following line is present in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>If you target Android 6.0 or earlier, a few extra steps are outlined below for installation and initialization.
1.9.0 changes targeting, so assignments for running experiments can change. Audiences and assignment rule conditions always see the configured application and environment names, whatever includeSystemAttributes is set to. The SDK no longer provides app_version, so set an app_version attribute yourself if you target on it. With includeSystemAttributes enabled, a publish now adds only sdk_name and sdk_version. See System Attributes and the changelog.
1.8.0 moves the asynchronous API of core-api from the streamsupport backport to the JDK. If your code names java8.util.concurrent.* or java8.util.function.* types from the SDK API, or implements HTTPClient, ContextDataProvider or ContextEventHandler, replace those imports with the java.util.concurrent and java.util.function types of the same name. If you only use the blocking API, recompile.
On Java 6 or 7, or Android below API level 24, depend on core-api-java6 instead of core-api. It keeps the backport types, so no code changes are needed.
The public unit getters remain compatible with 1.6.3: getUnit returns a String and getUnits returns Map<String, String>. Unit UIDs may now also be numeric; numeric values are returned by the new getUnitValue and getUnitValues accessors, while the original getters return their string form.
Context reads retain the 1.6.3 lifecycle behavior. Before ready they throw "ABSmartly Context is not yet ready"; while closing and after close they throw "ABSmartly Context is closing" and "ABSmartly Context is closed", respectively. Custom-field reads remain available once the context is ready, including while closing and after close.
To install the ABSmartly SDK, place the following in your build.gradle and replace {VERSION} with the latest SDK version available in MavenCentral.
Java 8 and later, Android API level 24 and later:
dependencies {
implementation 'com.absmartly.sdk:core-api:{VERSION}'
}Java 6 and 7, Android below API level 24:
dependencies {
implementation 'com.absmartly.sdk:core-api-java6:{VERSION}'
}To install the ABSmartly SDK, place the following in your pom.xml and replace {VERSION} with the latest SDK version available in MavenCentral.
Java 8 and later:
<dependency>
<groupId>com.absmartly.sdk</groupId>
<artifactId>core-api</artifactId>
<version>{VERSION}</version>
</dependency>Java 6 and 7:
<dependency>
<groupId>com.absmartly.sdk</groupId>
<artifactId>core-api-java6</artifactId>
<version>{VERSION}</version>
</dependency>When targeting Android 6.0 or earlier, the default Java Security Provider will not work. Using Conscrypt is recommended. Follow these instructions to install it as dependency.
ProGuard is a command-line tool that reduces app size by shrinking bytecode and obfuscates the names of classes, fields and methods. It's an ideal fit for developers working with Java or Kotlin who are primarily interested in an Android optimizer. If you are using Proguard, you will need to add the following rule to your Proguard configuration file. This prevent proguard to change data classes used by the SDK and the missing of this rule will result in problems in the serialization/deserialization of the data.
-keep public class com.absmartly.sdk.json.** { *; }
Please follow the installation instructions before trying the following code:
This example assumes an Api Key, an Application, and an Environment have been created in the A/B Smartly web console.
import com.absmartly.sdk.*;
final ABSmartly sdk = ABSmartly.builder()
.endpoint("https://your-company.absmartly.io/v1")
.apiKey(System.getenv("ABSMARTLY_APIKEY"))
.application("website")
.environment("production")
.build();The builder pattern lets you configure the SDK with named parameters, removing the need to configure ClientConfig and ABSmartlyConfig manually.
For use cases where you need full control over the Client and configuration:
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website")
.setEnvironment("development");
final Client absmartlyClient = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);SDK Options
| Config | Type | Required? | Default | Description |
|---|---|---|---|---|
| endpoint | String |
✅ | null |
The URL to your API endpoint. Most commonly "https://your-company.absmartly.io/v1" |
| apiKey | String |
✅ | null |
Your API key which can be found on the Web Console. |
| environment | String |
✅ | null |
The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
| application | String |
✅ | null |
The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
| applicationVersion | String or long |
❌ | null |
The version of your application, e.g. "2.4.1". Sent as the X-Application-Version request header only when it is a whole number of at most 18 digits; anything longer, negative or non-numeric (such as "2.4.1") is sent as 0. It is not exposed to targeting as app_version; set an app_version attribute yourself if you want to target on it. |
| timeout | int |
❌ | 3000 |
HTTP connection timeout in milliseconds |
| retries | int |
❌ | 5 |
Maximum number of retry attempts for failed HTTP requests |
| contextEventLogger | ContextEventLogger |
❌ | null |
Callback to handle SDK events (ready, exposure, goal, etc.) |
| contextDataProvider | ContextDataProvider |
❌ | auto | Custom provider for context data (advanced usage) |
| contextEventHandler | ContextEventHandler |
❌ | auto | Custom handler for publishing events (advanced usage) |
| variableParser | VariableParser |
❌ | auto | Custom parser for experiment variables (advanced usage) |
| audienceDeserializer | AudienceDeserializer |
❌ | auto | Custom deserializer for audience data (advanced usage) |
| scheduler | ScheduledExecutorService |
❌ | auto | Custom scheduler for context refresh (advanced usage) |
| httpClient | HTTPClient |
❌ | auto | Custom HTTP client implementation (advanced usage) |
When targeting Android 6.0 or earlier, set the default Java Security Provider for SSL to Conscrypt by creating the Client instance as follows:
import com.absmartly.sdk.*;
import org.conscrypt.Conscrypt;
// ...
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website")
.setEnvironment("development");
final DefaultHTTPClientConfig httpClientConfig = DefaultHTTPClientConfig.create()
.setSecurityProvider(Conscrypt.newProvider());
final DefaultHTTPClient httpClient = DefaultHTTPClient.create(httpClientConfig);
final Client absmartlyClient = Client.create(clientConfig, httpClient);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
// ...final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
final Context context = sdk.createContext(contextConfig)
.waitUntilReadyAsync()
.thenAccept(ctx -> System.out.printf("context ready!"));Creating a context involves a round-trip to the A/B Smartly event collector. We can avoid repeating the round-trip on the client-side by re-using data previously retrieved.
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();
final ContextConfig anotherContextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8");
final Context anotherContext = sdk.createContextWith(anotherContextConfig, context.getData());
assert(anotherContext.isReady()); // no need to waitFor long-running contexts, the context is usually created once when the application is first started.
However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
To mitigate this, we can use the setRefreshInterval() method on the context config.
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setRefreshInterval(TimeUnit.HOURS.toMillis(4)); // every 4 hoursAlternatively, the refresh() method can be called manually.
The refresh() method pulls updated experiment data from the A/B Smartly collector and will trigger recently started experiments when getTreatment() is called again.
context.refresh();You can add additional units to a context by calling the setUnit() or the setUnits() method.
This method may be used for example, when a user logs in to your application, and you want to use the new unit type to the context.
Please note that you cannot override an already set unit type as that would be a change of identity, and will throw an exception. In this case, you must create a new context instead.
The setUnit() and setUnits() methods can be called before the context is ready.
context.setUnit("db_user_id", "1000013");
context.setUnits(Map.of(
"db_user_id", "1000013"
));if (context.getTreatment("exp_test_experiment") == 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}final Object variable = context.getVariable("my_variable");Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure.
The A/B Smartly SDK provides a peekTreatment() method for that.
if (context.peekTreatment("exp_test_experiment") == 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}final Object variable = context.peekVariable("my_variable");During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the setOverride() and/or setOverrides() methods.
The setOverride() and setOverrides() methods can be called before the context is ready.
context.setOverride("exp_test_experiment", 1);
context.setOverrides(Map.of(
"exp_test_experiment", 1,
"exp_another_experiment", 0
));The setAttribute() and setAttributes() methods can be called before the context is ready.
context.setAttribute("user_agent", req.getHeader("User-Agent"));
context.setAttributes(Map.of(
"customer_age", "new_customer"
));The configured application and environment names are always available as variables to audience filters and
assignment rule conditions, regardless of any flag. An attribute you set with the same name takes precedence, even
one set after the context is created (it re-checks cached assignments). Names that are unset or empty are left out.
These are not real attributes: they are not published (the collector adds application and environment to every
event server-side) and getAttributes()/getAttribute() do not return them. A context created without a client
(with the public Context.create, or through an ABSmartly with no client configured) has no application or
environment to expose.
app_version is no longer supplied to targeting. ClientConfig.setApplicationVersion only controls the
X-Application-Version request header; set an app_version attribute yourself if you want to target on it.
Set includeSystemAttributes to also add sdk_name and sdk_version to the attributes of every publish:
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setIncludeSystemAttributes(true);They are stamped with the time of the earliest exposure or goal in the publish, and one you have set yourself with
the same name is sent only as your value. The option no longer publishes application, environment or
app_version. It is disabled by default.
Experiments can define assignment rules on the Web Console. They are evaluated in order, and the first matching rule decides the variant, taking precedence over holdout suppression, audience targeting, traffic allocation and custom assignments. Holdouts are still evaluated and still record their own exposures.
- An
assignrule gives a fixed variant. - A
splitrule randomizes the unit over its own percentages, e.g.20/30/50. While the experiment's unit is missing, a split rule gives the full-on variant (0 for an experiment that is not full-on); once the unit is set, the variant is re-randomized, unless it was already exposed.
If the first matching rule's variant is out of range, or its split does not have one percentage per variant, it is ignored and normal assignment applies; later rules are not tried.
A rule matches when its conditions evaluate to true against the context attributes and, if it is scoped to
environments, the client's environment is one of them. A rule without conditions always matches, and an empty
environments list means every environment. Environment names are case-sensitive. Contexts without a client have no
environment, so rules scoped to environments never match there. Rule-assigned exposures are flagged ruleOverride so
the backend can exclude them from analysis. setOverride() still takes precedence over every rule.
Conditions can compare versions with semver_eq, semver_gt, semver_gte, semver_lt and semver_lte, for
example against app_version. A leading v or V and build metadata are ignored, missing parts count as 0, and a
pre-release is lower than its release (1.0.0-beta < 1.0.0).
The SDK sends X-Agent: absmartly-java-sdk/<version> when it publishes events, so the backend can report which SDK
versions your applications use.
Goals are created in the A/B Smartly web console.
context.track("payment", Map.of(
"item_count", 1,
"total_amount", 1999.99
));Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding.
You can explicitly call the publish() or publishAsync() methods.
context.publish();The close() and closeAsync() methods will ensure all events have been published to the A/B Smartly collector, like publish(), and will also "seal" the context, throwing an error if any method that could generate an event is called.
context.close();Switchback experiments need no new API: getTreatment, peekTreatment and the variable methods return the variant for the current time period, and the SDK emits one exposure per period while time moves forward. A switchback is clustered by attribute: the experiment links one or more unit types to an attribute path, so set those units and attributes on the context. The first linked unit whose attribute holds a value serves the experiment, and that value is its cluster. Units of the experiment's linked types that disagree on the value, carry a value outside the experiment's allowed values, or carry no value at all get the control variant and record no exposure. Holdouts do not apply to switchbacks. Assignment rules do apply, ahead of the time schedule.
context.setUnit("store_id", "store-0042");
context.setAttribute("store", Collections.singletonMap("region", "lisbon"));
int treatment = context.getTreatment("exp_switchback_pricing");The order of an experiment's switchbackClusters map is part of its meaning (the first linked unit with a value serves), so Experiment.equals and hashCode are order-sensitive on that field: experiments whose maps hold the same entries in a different order are not equal.
See SWITCHBACK.md for the serving rules, the exposure deduplication bound, the minimum SDK version and how older SDKs behave.
The A/B Smartly SDK can be instantiated with an event logger used for all contexts.
In addition, an event logger can be specified when creating a particular context, in the ContextConfig.
public class CustomEventLogger implements ContextEventLogger {
@Override
public void handleEvent(Context context, ContextEventLogger.EventType event, Object data) {
switch (event) {
case Exposure:
final Exposure exposure = (Exposure)data;
System.out.printf("exposed to experiment %s", exposure.name);
break;
case Goal:
final GoalAchievement goal = (GoalAchievement)data;
System.out.printf("goal tracked: %s", goal.name);
break;
case Error:
System.out.printf("error: %s", data);
break;
case Publish:
case Ready:
case Refresh:
case Close:
break;
}
}
}Usage:
// For all contexts, during SDK initialization
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create();
sdkConfig.setContextEventLogger(new CustomEventLogger());
// OR, alternatively, during a particular context initialization
final ContextConfig contextConfig = ContextConfig.create();
contextConfig.setEventLogger(new CustomEventLogger());Event Types
| Event | When | Data |
|---|---|---|
Error |
Context receives an error |
Throwable object |
Ready |
Context turns ready |
ContextData used to initialize |
Refresh |
Context.refresh() method succeeds |
ContextData used to refresh |
Publish |
Context.publish() method succeeds |
PublishEvent sent to collector |
Exposure |
Context.getTreatment() succeeds on first exposure |
Exposure enqueued for publishing |
Goal |
Context.track() method succeeds |
GoalAchievement enqueued for publishing |
Close |
Context.close() method succeeds the first time |
null |
// Application.java
import com.absmartly.sdk.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Value;
@SpringBootApplication
public class Application {
@Value("${absmartly.endpoint}")
private String endpoint;
@Value("${absmartly.apiKey}")
private String apiKey;
@Value("${absmartly.application}")
private String application;
@Value("${absmartly.environment}")
private String environment;
@Bean
public ABSmartly absmartly() {
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint(endpoint)
.setAPIKey(apiKey)
.setApplication(application)
.setEnvironment(environment);
final Client client = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(client);
return ABSmartly.create(sdkConfig);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// application.properties
absmartly.endpoint=https://your-company.absmartly.io/v1
absmartly.apiKey=YOUR-API-KEY
absmartly.application=website
absmartly.environment=production
// ProductController.java
import com.absmartly.sdk.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpSession;
@Controller
public class ProductController {
@Autowired
private ABSmartly absmartly;
@GetMapping("/product")
public ModelAndView showProduct(HttpSession session) {
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", session.getId());
final ModelAndView mav = new ModelAndView();
try (Context context = absmartly.createContext(contextConfig)
.waitUntilReady()) {
final int treatment = context.getTreatment("exp_product_layout");
if (treatment == 0) {
mav.setViewName("product_control");
} else {
mav.setViewName("product_treatment");
}
}
return mav;
}
}// ABSmartlyProducer.java
import com.absmartly.sdk.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
@ApplicationScoped
public class ABSmartlyProducer {
@Produces
@ApplicationScoped
public ABSmartly produceABSmartly() {
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint(System.getenv("ABSMARTLY_ENDPOINT"))
.setAPIKey(System.getenv("ABSMARTLY_API_KEY"))
.setApplication("website")
.setEnvironment(System.getenv("ENV"));
final Client client = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(client);
return ABSmartly.create(sdkConfig);
}
}
// ProductResource.java
import com.absmartly.sdk.*;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.servlet.http.HttpServletRequest;
@Path("/product")
public class ProductResource {
@Inject
private ABSmartly absmartly;
@Inject
private HttpServletRequest request;
@GET
public Response getProduct() {
final String sessionId = request.getSession().getId();
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", sessionId);
try (Context context = absmartly.createContext(contextConfig)
.waitUntilReady()) {
final int treatment = context.getTreatment("exp_product_layout");
return Response.ok()
.entity(Map.of("treatment", treatment))
.build();
}
}
}// MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.absmartly.sdk.*;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static ABSmartly sdk;
private Context absmartlyContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize SDK once (typically in Application class)
if (sdk == null) {
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("android-app")
.setEnvironment("production");
final Client client = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(client);
sdk = ABSmartly.create(sdkConfig);
}
// Create context for this user
String deviceId = getDeviceId(); // Get from SharedPreferences
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("device_id", deviceId);
final Context contextInstance = sdk.createContext(contextConfig);
absmartlyContext = contextInstance;
contextInstance.waitUntilReadyAsync()
.thenAccept(ctx -> {
runOnUiThread(() -> setupUI(ctx));
})
.exceptionally(throwable -> {
runOnUiThread(() -> setupUIWithDefault());
return null;
});
}
private void setupUI(Context context) {
int treatment = context.getTreatment("exp_button_color");
if (treatment == 0) {
setContentView(R.layout.activity_main_control);
} else {
setContentView(R.layout.activity_main_treatment);
}
}
private void setupUIWithDefault() {
setContentView(R.layout.activity_main_control);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (absmartlyContext != null) {
absmartlyContext.close();
}
}
private String getDeviceId() {
// IMPORTANT: Device ID must be persisted across app sessions in SharedPreferences
// to ensure consistent experiment assignments for the same user/device.
// This example uses a random UUID for demonstration purposes only.
return UUID.randomUUID().toString();
}
}Configure timeout for individual requests using DefaultHTTPClientConfig:
import com.absmartly.sdk.*;
// Create HTTP client with custom timeout
final DefaultHTTPClientConfig httpClientConfig = DefaultHTTPClientConfig.create()
.setConnectTimeout(1500) // 1.5 seconds
.setConnectionRequestTimeout(1500);
final DefaultHTTPClient httpClient = DefaultHTTPClient.create(httpClientConfig);
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website")
.setEnvironment("development");
final Client client = Client.create(clientConfig, httpClient);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(client);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "abc123");
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();Cancel inflight requests when user navigates away:
import com.absmartly.sdk.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.*;
public class CancellableContextExample {
public static void main(String[] args) throws Exception {
final ABSmartly sdk = ABSmartly.builder()
.endpoint("https://your-company.absmartly.io/v1")
.apiKey("YOUR-API-KEY")
.application("website")
.environment("development")
.build();
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("session_id", "abc123");
final Context context = sdk.createContext(contextConfig);
// Create future for context initialization
final CompletableFuture<Context> future = context.waitUntilReadyAsync();
// Cancel after 1.5 seconds if not ready
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> {
if (!future.isDone()) {
future.cancel(true);
System.out.println("Context creation cancelled");
}
}, 1500, TimeUnit.MILLISECONDS);
try {
final Context readyContext = future.get();
System.out.println("Context ready!");
readyContext.close();
} catch (CancellationException e) {
System.out.println("Context creation was cancelled");
} catch (ExecutionException e) {
System.out.println("Context creation failed: " + e.getCause());
} finally {
scheduler.shutdown();
}
}
}import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.absmartly.sdk.*;
import java.util.concurrent.CompletableFuture;
public class MainActivity extends AppCompatActivity {
private static ABSmartly sdk; // Initialize SDK once (typically in Application class)
private CompletableFuture<Context> contextFuture;
private Context absmartlyContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("device_id", getDeviceId());
absmartlyContext = sdk.createContext(contextConfig);
contextFuture = absmartlyContext.waitUntilReadyAsync();
contextFuture.thenAccept(ctx -> {
runOnUiThread(() -> setupUI(ctx));
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel ongoing context creation if activity is destroyed
if (contextFuture != null && !contextFuture.isDone()) {
contextFuture.cancel(true);
}
if (absmartlyContext != null) {
absmartlyContext.close();
}
}
}A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.