Set up a Java source in your dashboard. You should be able to see a write key for this source:
You will also need a data plane URL. Refer to the Dashboard Overview guide for more information on the data plane URL and where to find it.
The Setup tab in the RudderStack dashboard (seen above) has the SDK installation snippet containing both the write key and the data plane URL. Copy it to integrate the Java SDK into your application.
Installing the Java SDK
As Bintray has sunset from 1st May, 2021, the Java SDK is now moved to Maven Central. All the versions from 1.0.1 will now be available in Maven Central only.
It is highly recommended to use the Maven build system to add the SDK to your project.
To install the RudderStack Java SDK, add the following lines of code to pom.xml:
To migrate to the Java SDK v3.0.0, set the data plane URL using setDataPlaneUrl("<DATA_PLANE_URL>") (as seen in the above section) instead of passing it as an argument.
Configuring the RudderStack client
You can configure your client based on the following methods in RudderClient.Builder:
Method
Type
Description
client
OkHttpClient
Sets a custom OkHttpClient. It is created by default.
setGZIP
Boolean
Gzips the event request.
Default value: true
log
Log
Sets the logging level for debugging. Available options are VERBOSE, DEBUG, ERROR, and NONE.
Default value: NONE
setDataPlaneUrl
String
Sets the data plane URL.
Default value: https://hosted.rudderlabs.com
setUploadURL
String
Sets the data plane URL - used for Segment compatibility.
Sets the executor service on which all HTTP requests are made.
Default value: SingleThreadExecutor
callback
Callback
Gets invoked when the client library processes an event.
Default value: Empty list.
forceTlsVersion1
-
Enforces TLS v1.
Default value: false
The following initialization methods are currently in beta:
Available method
Type
Description
messageTransformer
MessageTransformer
Adds a transformer for the message before uploading it.
Default value: null
messageInterceptor
MessageInterceptor
Add a MessageInterceptor for intercepting messages before sending to RudderStack.
Default value: null
flushQueueSize
Integer
Sets the queue size at which the SDK triggers the flush requests.
Default value: 250
maximumQueueSizeInBytes
Integer
Sets the maximum queue size at which the flush requests are triggered.
Default value: 1024*500 Bytes
flushInterval
Long, TimeUnit
Sets the time interval which the SDK flushes the queue.
Default value: 10 seconds
threadFactory
ThreadFactory
Sets the thread factory used to create the threads.
Default value: null
plugin
Plugin
Used to configure the builder.
Default value: null
Sending events
RudderStack does not store or persist the user state in any of the server-side SDKs.
Unlike the client-side SDKs that deal with only a single user at a given time, the server-side SDKs deal with multiple users simultaneously. Therefore, you must specify either the userId or anonymousIdevery time while making any API calls supported by the Java SDK.
Identify
The identify call lets you identify a visiting user and associate them to their actions. It also lets you record the traits about them like their name, email address, etc.
A sample identify call made using the Java SDK is shown below:
The page method parameters are as described below:
Field
Type
Description
userId Required, if anonymousId is absent.
String
Unique identifier for a user in your database.
anonymousId Required, if userId is absent.
String
Use this field to set an identifier in cases where there is no unique user identifier.
name Required
String
Name of the viewed page.
properties
Object
An optional dictionary of the properties associated with the viewed page, like url or referrer.
context
Object
An optional dictionary of information that provides context about the event. It is not directly related to the API call.
integrations
Object
An optional dictionary containing the destinations to be enabled or disabled.
timestamp
Timestamp in ISO 8601 format
The timestamp of the event’s arrival.
Screen
The screen call is the mobile equivalent of the page call. It lets you record the screen views on your mobile app along with other relevant information about the screen.
The screen method parameters are as described below:
Field
Type
Description
userId Required, if anonymousId is absent.
String
Unique identifier for a user in your database.
anonymousId Required, if userId is absent.
String
Use this field to set an identifier in cases where there is no unique user identifier.
name Required
String
Name of the viewed screen.
properties
Object
An optional dictionary of the properties associated with the screen, like url or referrer.
context
Object
An optional dictionary of information that provides context about the event. It is not directly related to the API call.
integrations
Object
An optional dictionary containing the destinations to be enabled or disabled.
timestamp
Timestamp in ISO 8601 format
The timestamp of the event’s arrival.
Group
The group call lets you link an identified user with a group, such as a company, organization, or an account. It also lets you record any custom traits or properties associated with that group.
A sample group call made using the Java SDK is shown below:
Use this field to set an identifier in cases where there is no unique user identifier.
groupId Required
String
Unique identifier of the group in your database.
traits
Object
An optional dictionary of the group’s traits like nameor email.
context
Object
An optional dictionary of information that provides context about the event. It is not directly related to the API call.
integrations
Object
An optional dictionary containing the destinations to be enabled or disabled.
timestamp
Timestamp in ISO 8601 format
The timestamp of the event’s arrival.
Alias
The alias call lets you merge different identities of a known user. It is an advanced method that lets you change the tracked user’s ID explicitly. You can use alias for managing the user’s identity in some of the downstream destinations.
RudderStack supports sending alias events only to select downstream destinations. Refer to the destination-specific documentation for more details.
The alias method parameters are as mentioned below:
Field
Type
Description
userId Required, if anonymousId is absent.
String
Unique identifier for a user in your database.
anonymousId Required, if userId is absent.
String
Use this field to set an identifier in cases where there is no unique user identifier.
previousId Required
String
The previous unique identifier of the user.
traits
Object
An optional dictionary of the user’s traits like name or email.
context
Object
An optional dictionary of information that provides context about the event. It is not directly related to the API call.
integrations
Object
An optional dictionary containing the destinations to be enabled or disabled.
timestamp
Timestamp in ISO 8601 format
The timestamp of the event’s arrival.
Filtering destinations
The Java SDK lets you enable or disable sending events to specifc destinations connected to the source. You can do so by passing the integrations object in your API calls:
If you pass any custom information in the context object, the SDK automatically merges it with the existing context, except the information contained in library.
Batching events
The RudderStack SDKs are built to support high performance environments. It is safe to use the Java SDK on a web server serving hundreds of requests per second.
Every SDK API you call does not result in a HTTP request but it is queued in the memory instead. RudderStack flushes the events in batches in the background, allowing faster operations.
The Java SDK has a maximum size limit of 500KB per batch request and 32KB per call.
The RudderStack HTTP Tracking API accepts batch requests upto 500KB. To avoid any errors while sending the event requests, make sure the single event payload size is below 32KB.
Flushing events
To flush your events, the Java SDK supports the flush method. It notifies the RudderStack client to upload the events and make sure no events are left in the queue at any given point.
A sample snippet highlighting the use of the flush method is shown below:
analytics.flush()
Blocking flush
By default, the Java SDK does not support blocking flush implicitly. You need to create a BlockingFlush class (handles a maximum of 65535 parallel calls to flush) or a TierBlockingFlush class (no limit on parallel calls) depending on your requirement.
Both BlockingFlush and TierBlockingFlush classes are not a part of the core Java SDK.
A sample snippet highlighting the use of BlockingFlush is shown below:
finalBlockingFlushblockingFlush=BlockingFlush.create();RudderAnalyticsanalytics=RudderAnalytics.builder("<WRITE_KEY>").plugin(blockingFlush.plugin()).setDataPlaneUrl("<DATA_PLANE_URL>").build();// ...YOUR CODE...
analytics.flush();// Triggers a flush.
blockingFlush.block();analytics.shutdown();// Shuts down after the flush is complete.
A detailed implementation of the BlockingFlush class is shown below. Note that this is just a sample code snippet and you can modify it as per your use case.
packagesample;importcom.rudderstack.sdk.java.analytics.RudderAnalytics;importcom.rudderstack.sdk.java.analytics.Callback;importcom.rudderstack.sdk.java.analytics.MessageTransformer;importcom.rudderstack.sdk.java.analytics.Plugin;importcom.rudderstack.sdk.java.analytics.messages.Message;importcom.rudderstack.sdk.java.analytics.messages.MessageBuilder;importjava.util.concurrent.Phaser;/*
* The {@link RudderAnalytics} class doesn't come with a blocking {@link RudderAnalytics#flush()} implementation
* out of the box. It's trivial to build one using a {@link Phaser} that monitors requests and is
* able to block until they're uploaded.
*/publicclassBlockingFlush{publicstaticBlockingFlushcreate(){returnnewBlockingFlush();}BlockingFlush(){this.phaser=newPhaser(1);}finalPhaserphaser;publicPluginplugin(){returnbuilder->{builder.messageTransformer(builder1->{phaser.register();returntrue;});builder.callback(newCallback(){@Overridepublicvoidsuccess(Messagemessage){phaser.arrive();}@Overridepublicvoidfailure(Messagemessage,Throwablethrowable){phaser.arrive();}});};}publicvoidblock(){phaser.arriveAndAwaitAdvance();}}
The above implementation restricts the maximum number of parties to 65535. If you try to create and use more parties, this class throws an error. To remove this limitation and use more parties, refer to the TierBlockingFlush section below.
TierBlockingFlush
To remove the limitations on the maximum number of supported parties, you can use the TierBlockingFlush class.
The following snippet highlights its use:
finalTierBlockingFlushblockingFlush=TierBlockingFlush.create();RudderAnalyticsanalytics=RudderAnalytics.builder("<WRITE_KEY>").plugin(blockingFlush.plugin()).setDataPlaneUrl("<DATA_PLANE_URL>").build();// ...YOUR CODE...
analytics.flush();// Trigger a flush.
blockingFlush.block();analytics.shutdown();// Shut down after the flush is complete.
The following snippet highlights a detailed implementation of the TierBlockingFlush class with support for more than 65535 parties. Note that this is just a sample code snippet and you can modify it as per your use case.
packagesample;importcom.rudderstack.sdk.java.analytics.Callback;importcom.rudderstack.sdk.java.analytics.Plugin;importcom.rudderstack.sdk.java.analytics.messages.Message;importjava.util.concurrent.Phaser;/**
* Blocking flush implementor for cases where parties exceed 65535
*/publicclassTierBlockingFlush{privatestaticfinalintMAX_PARTIES_PER_PHASER=(1<<16)-2;// max a phaser can accommodate
publicstaticTierBlockingFlushcreate(){returnnewTierBlockingFlush(MAX_PARTIES_PER_PHASER);}privateTierBlockingFlush(intmaxPartiesPerPhaser){this.currentPhaser=newPhaser(1);this.maxPartiesPerPhaser=maxPartiesPerPhaser;}privatePhasercurrentPhaser;privatefinalintmaxPartiesPerPhaser;publicPluginplugin(){returnbuilder->{builder.messageTransformer(messageTransformationBuilder->{currentPhaser=currentPhaser.getRegisteredParties()==maxPartiesPerPhaser?newPhaser(currentPhaser):currentPhaser;currentPhaser.register();returntrue;});builder.callback(newCallback(){@Overridepublicvoidsuccess(Messagemessage){onResult();}@Overridepublicvoidfailure(Messagemessage,Throwablethrowable){onResult();}privatevoidonResult(){if(currentPhaser.getUnarrivedParties()==0){currentPhaser=currentPhaser.getParent();}currentPhaser.arrive();}});};}publicvoidblock(){currentPhaser.arriveAndAwaitAdvance();}}
Logging
To see the data that is sent over HTTP when debugging any issues, enable the SDK’s verbose logging feature.
Refer to the sample snippet for more information on setting the logs using the Java SDK.
Refer to the sample app for more information on using the logging plugin during the SDK initialization.
Gzipping requests
The Gzip feature is enabled by default in the Java SDK version 3.0.0.
The Java SDK automatically gzips requests. It also lets you do so using interceptors in OkHttp.
Refer to the sample app in the Java SDK repository for a working example.
To disable the Gzip feature using the setGZIP API while initializing the SDK, run the following snippet:
Note that if you pass the OkHttp client using the client API while initializing your SDK, then it is preferred over the default Gzip behavior. It means that even if you use the setGZIP API to enable/disable Gzip requests, the behavior will be determined based on the interceptor passed in the OkHttp client.
To gzip requests on a self-hosted data plane, make sure your rudder-server version is 1.4 or higher. Otherwise, your events might fail.
FAQ
Can I use the ImmutableMap class?
Yes, you can use the ImmutableMap class via the Guava library or use the Java maps.
How do I flush events on demand?
To flush your events on demand, call the flush method as shown:
analytics.flush()
How does the Java SDK handle events larger than 32KB?
The Java SDK accepts and sends each event greater than 32KB as a single batch and sends them to the backend.
Does the Java SDK support event ordering?
The Java SDK does not support event ordering by default.
This site uses cookies to improve your experience while you navigate through the website. Out of
these
cookies, the cookies that are categorized as necessary are stored on your browser as they are as
essential
for the working of basic functionalities of the website. We also use third-party cookies that
help
us
analyze and understand how you use this website. These cookies will be stored in your browser
only
with
your
consent. You also have the option to opt-out of these cookies. But opting out of some of these
cookies
may
have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This
category only includes cookies that ensures basic functionalities and security
features of the website. These cookies do not store any personal information.
This site uses cookies to improve your experience. If you want to
learn more about cookies and why we use them, visit our cookie
policy. We'll assume you're ok with this, but you can opt-out if you wish Cookie Settings.