Instrument and configure the JRE Java SDK
Use this page after your first event to track events, user and group properties, and revenue, and to configure middleware, data delivery, and logging. For setup, go to Get started with the JRE Java SDK. For signatures and defaults, go to the JRE Java SDK reference. For changes between versions, go to the Java SDK changelog.
The examples assume this setup, and imports from com.amplitude, org.json, and java.util:
Amplitude client = Amplitude.getInstance();
client.init("AMPLITUDE_API_KEY");
Track events
The SDK uses the HTTP V2 API, and every event follows its rules. Each event needs eventType and at least one of userId or deviceId.
Track a custom event
Create an Event with a name and a user ID, then pass it to logEvent(). Add properties with addEventProperty(), or pass a whole map with setEventProperties(). addEventProperty() and setEventProperties() require 1.13.0 or later.
Event event = new Event("Button Clicked", "user-12345");
event.addEventProperty("button_id", "checkout")
.addEventProperty("hover_time_ms", 320);
client.logEvent(event);
{
"event_type": "Button Clicked",
"user_id": "user-12345",
"event_properties": { "button_id": "checkout", "hover_time_ms": 320 }
}
On versions before 1.13.0, assign a JSONObject to the eventProperties field instead:
Event event = new Event("Button Clicked", "user-12345");
event.eventProperties = new JSONObject()
.put("button_id", "checkout")
.put("hover_time_ms", 320);
client.logEvent(event);
String values longer than 1,000 characters are cut to 1,000, and an object can hold at most 1,024 keys. Go to Limits.
Set user properties
User properties on any event update the user's profile. To update them without a user action, log an $identify event:
Event identify = new Event("$identify", "user-12345");
identify.addUserProperty("team", "red")
.addUserProperty("running_times", Arrays.asList(1, 2, 4, 8));
client.logEvent(identify);
{
"event_type": "$identify",
"user_id": "user-12345",
"user_properties": { "team": "red", "running_times": [1, 2, 4, 8] }
}
Don't track user data that your privacy terms don't allow.
Assign a user to a group
Groups let you count organizations, teams, or accounts instead of users. Groups require the Accounts add-on. A group has a type, such as orgId, and a name, such as 10. A user can belong to several groups of one type: pass a list of names.
To put a user in a group, log an $identify event that sets the group in both groups and userProperties:
Event setGroup = new Event("$identify", "user-12345");
setGroup.addGroup("orgId", 10)
.addGroup("sport", Arrays.asList("tennis", "soccer"))
.addUserProperty("orgId", 10)
.addUserProperty("sport", Arrays.asList("tennis", "soccer"));
client.logEvent(setGroup);
{
"event_type": "$identify",
"user_id": "user-12345",
"groups": { "orgId": 10, "sport": ["tennis", "soccer"] },
"user_properties": { "orgId": 10, "sport": ["tennis", "soccer"] }
}
The $identify event sets orgId and sport as user properties, and replaces any earlier value for those group types. To credit one event to a group without changing the user's groups, set groups on that event only:
Event event = new Event("Report Exported", "user-12345");
event.addGroup("orgId", 10);
client.logEvent(event);
Set group properties
To set properties on a group itself, log a $groupidentify event with groups and groupProperties. The update affects events from then on.
Event groupIdentify = new Event("$groupidentify", "user-12345");
groupIdentify.addGroup("org", "engineering")
.addGroupProperty("technology", "java")
.addGroupProperty("location", "sf");
client.logEvent(groupIdentify);
Track revenue
Set price (or revenue) on the event. When you set price or revenue, the SDK also sends quantity, productId, revenueType, and currency. The SDK sends quantity as 1 when you don't set it. currency requires 1.12.5 or later.
Event order = new Event("Order Completed", "user-12345");
order.price = 9.99;
order.quantity = 2;
order.productId = "sku-123";
order.revenueType = "purchase";
order.currency = "USD";
client.logEvent(order);
{
"event_type": "Order Completed",
"user_id": "user-12345",
"price": 9.99,
"quantity": 2,
"productId": "sku-123",
"revenueType": "purchase",
"currency": "USD"
}
Amplitude computes revenue as price × quantity. Use a negative price for refunds.
Set device and location fields
The SDK collects no device, OS, or location data. Set the fields you have on each event:
Event event = new Event("Button Clicked", "user-12345", "device-67890");
event.platform = "Server";
event.osName = "Linux";
event.deviceModel = "c7g.large";
event.country = "United States";
event.ip = "203.0.113.24";
event.appVersion = "2.4.1";
client.logEvent(event);
For every field, go to Event fields. Set ip to the end user's address when you have it. With $remote, Amplitude uses the address of the upload request, which is your server's.
Send events to more than one project
Each name passed to getInstance() is an independent instance, with its own API key, queue, settings, and threads:
Amplitude billing = Amplitude.getInstance("billing");
billing.init("PROJECT_A_API_KEY");
Amplitude product = Amplitude.getInstance("product");
product.init("PROJECT_B_API_KEY");
billing.logEvent(new Event("Invoice Paid", "user-12345"));
Identity and sessions
How the SDK identifies users
The SDK doesn't store identity. Each Event carries its own userId and deviceId, and the constructor throws IllegalArgumentException when both are null. Pass the ID of the user the event belongs to on every call. In a server that handles many users, take it from the request, never from a shared field.
When an event has a userId but no deviceId, Amplitude creates the device ID from the user ID. Amplitude rejects IDs shorter than five characters.
Allow shorter IDs
If your IDs can be shorter than five characters, lower the minimum Amplitude accepts. The SDK sends the minimum with each upload.
client.setOptions(new Options().setMinIdLength(3));
client.logEvent(new Event("Button Clicked", "u42"));
Attach a session ID
The SDK doesn't track sessions: sessionId is -1 (no session) unless you set it. To group server events into a session, set sessionId to the session's start time in milliseconds on each of its events:
long sessionStart = 1794340000000L; // from your session store
Event event = new Event("Button Clicked", "user-12345");
event.sessionId = sessionStart;
client.logEvent(event);
Middleware
Middleware runs your code on every event before it joins the upload queue. Use it to add fields, change events, drop events, or send copies elsewhere. Requires 1.6.0 or later.
How middleware runs
logEvent() runs the middleware chain on the calling thread, in the order you added each middleware. Each middleware receives a MiddlewarePayload with the event and an optional extra. Each middleware calls next.run(payload) to pass the event on. When the last middleware calls next, the event joins the queue. If any middleware doesn't call next, the SDK drops the event silently: no upload and no callback.
Enrich events
client.addEventMiddleware((payload, next) -> {
payload.event.appVersion = "2.4.1";
payload.event.addEventProperty("region", "us-west-2");
next.run(payload);
});
client.logEvent(new Event("Job Completed", "user-12345"));
{
"event_type": "Job Completed",
"app_version": "2.4.1",
"event_properties": { "region": "us-west-2" }
}
Drop events
Return without calling next to drop an event:
client.addEventMiddleware((payload, next) -> {
if (payload.event.userId != null && payload.event.userId.startsWith("test-")) {
return; // drop events from test accounts
}
next.run(payload);
});
client.logEvent(new Event("Button Clicked", "test-user-1"));
client.logEvent(new Event("Button Clicked", "user-12345"));
Pass data to middleware
Pass a MiddlewareExtra (a HashMap<String, Object>) to logEvent() to give middleware data that isn't part of the event. The SDK doesn't send it to Amplitude.
client.addEventMiddleware((payload, next) -> {
if (payload.extra != null && payload.extra.containsKey("tenant")) {
payload.event.addEventProperty("tenant", payload.extra.get("tenant"));
}
next.run(payload);
});
MiddlewareExtra extra = new MiddlewareExtra();
extra.put("tenant", "acme");
client.logEvent(new Event("Page Rendered", "user-12345"), extra);
A middleware class at the top level of your code works the same way. Implement Middleware:
class LoggingMiddleware implements Middleware {
@Override
public void run(MiddlewarePayload payload, MiddlewareNext next) {
System.out.println("Amplitude event: " + payload.event.eventType);
next.run(payload);
}
}
client.addEventMiddleware(new LoggingMiddleware());
client.logEvent(new Event("Button Clicked", "user-12345"));
Data delivery
How the SDK uploads events
logEvent() adds the event to a queue in memory and returns. The SDK starts an upload when either of these happens first:
- The queue holds 10 events (
setEventUploadThreshold()). - 10 seconds pass after the first event entered an empty queue (
setEventUploadPeriodMillis()).
Each upload sends the whole queue in one request, on a pool of 20 upload threads. When a request fails with a retryable error, the SDK groups the events by user and device. The SDK retries each group up to 12 times on a pool of 10 retry threads. Retries wait 100 milliseconds at first, and up to 3.2 seconds. At most 16,000 events wait for a retry. The SDK writes nothing to disk, so you lose events still in memory when the JVM stops.
Tune upload batching
client.setEventUploadThreshold(50)
.setEventUploadPeriodMillis(5000);
client.logEvent(new Event("Button Clicked", "user-12345"));
The threshold doesn't cap the request size: flushEvents() and the timer send everything in the queue.
Flush and shut down
Call flushEvents(), then shutdown(), when your program finishes, a job ends, or a serverless function returns. flushEvents() starts an upload of the queue and returns immediately. shutdown() stops the SDK's threads, lets uploads already started finish, and doesn't flush. Requires 1.10.0 or later.
| What you do | What happens |
|---|---|
flushEvents(), then shutdown() | Events upload. The JVM exits up to 60 seconds after the upload, when an idle SDK thread times out. |
shutdown() only | You lose queued events. About 10 seconds later, the scheduled upload fails with Exception in thread "Thread-0" java.util.concurrent.RejectedExecutionException. |
| Neither, after at least one upload | The JVM never exits, because the SDK's threads stay alive. |
To exit as soon as the upload finishes, wait for the event's callback, then exit:
CountDownLatch done = new CountDownLatch(1);
client.logEvent(new Event("Batch Finished", "user-12345"), new AmplitudeCallbacks() {
@Override
public void onLogEventServerResponse(Event event, int status, String message) {
done.countDown();
}
});
client.flushEvents();
done.await(30, TimeUnit.SECONDS);
client.shutdown();
System.exit(0);
When you send many events, count the callbacks you expect, or set an instance callback with setCallbacks(). In a long-running service, run the same steps in a JVM shutdown hook. flushEvents() alone isn't enough there: the JVM halts as soon as the hook returns, so the hook must wait for the upload.
shutdown() also removes the instance from the registry. A later Amplitude.getInstance() with the same name returns a new instance that you must init() again.
Get upload results
Set an instance-wide callback with setCallbacks(), or pass one to logEvent() for a single event. When you set both, both run, and the instance callback runs first. Callbacks run on SDK threads, so keep them short and thread-safe.
client.setCallbacks(new AmplitudeCallbacks() {
@Override
public void onLogEventServerResponse(Event event, int status, String message) {
if (status != 200) {
System.err.println("Amplitude upload failed: " + status + " " + message);
}
}
});
client.logEvent(new Event("Button Clicked", "user-12345"));
For every status and message, go to Read the upload result. Instance callbacks require 1.4.0 or later, and per-event callbacks require 1.5.0 or later.
Send events to the EU data center
The SDK has no region setting. For a project in the EU data center, set the EU endpoint after init():
client.setServerUrl("https://api.eu.amplitude.com/2/httpapi");
client.logEvent(new Event("Button Clicked", "user-12345"));
For batch mode in the EU, use https://api.eu.amplitude.com/batch.
Send large batches to the Batch API
Batch mode sends to the Batch Event Upload API, which accepts larger requests and has higher rate limits. Amplitude may delay ingesting batch-mode data under load, so use it for imports and scheduled jobs, not real-time tracking. Call useBatchMode(true) after init(), because init() turns batch mode off.
client.useBatchMode(true);
client.logEvent(new Event("Record Imported", "user-12345"));
Batch mode uses the same threshold and period as regular uploads. Batch mode has no effect when you set a custom URL with setServerUrl().
Send events through a proxy
To send events through your own proxy server that forwards them to Amplitude, set the proxy URL with setServerUrl(). The URL must start with https://. The SDK opens every request as HTTPS, so an http:// URL fails each upload with a ClassCastException.
client.setServerUrl("https://amplitude-proxy.example.com/2/httpapi");
client.logEvent(new Event("Button Clicked", "user-12345"));
Route uploads through an HTTP proxy
If outbound traffic must pass through a forward proxy, set a java.net.Proxy. Requires 1.9.0 or later.
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
client.logEvent(new Event("Button Clicked", "user-12345"));
To stop using the proxy, call client.setProxy(Proxy.NO_PROXY).
Add request headers
Add HTTP headers to every upload request, for example for a proxy that needs them. Requires 1.7.0 or later.
client.setOptions(new Options()
.addHeader("X-Request-Source", "billing-service")
.setMinIdLength(5));
client.logEvent(new Event("Button Clicked", "user-12345"));
setOptions() replaces earlier options, so set the minimum ID length and headers in one Options object.
Set a flush timeout
By default, an upload task waits as long as its request takes, up to the 10-second connect and read timeouts. To cap the wait, set a flush timeout in milliseconds. When the flush timeout expires, the SDK reports the events to callbacks with status 0 and doesn't retry them. Requires 1.10.0 or later.
client.setFlushTimeout(5000L);
client.logEvent(new Event("Button Clicked", "user-12345"));
Use your own thread pools
Replace the pool of 20 upload threads or 10 retry threads, for example to share a pool or to limit threads. shutdown() shuts down the pools you pass. Requires 1.12.4 or later.
client.setSendThreadPool(Executors.newFixedThreadPool(4))
.setRetryThreadPool(Executors.newFixedThreadPool(2));
client.logEvent(new Event("Button Clicked", "user-12345"));
Slow down when the SDK is busy
High-volume senders can check shouldWait() before each event. Requires 1.6.1 or later. shouldWait() returns true when any of these applies:
- The queue is over the threshold.
- 16,000 events wait for a retry.
setRecordThrottledId(true)is on, and Amplitude recently throttled the event's user or device.
client.setRecordThrottledId(true);
Event event = new Event("Row Synced", "user-12345");
while (client.shouldWait(event)) {
Thread.sleep(100);
}
client.logEvent(event);
Add tracking plan and source information
Attach your tracking plan version and the name of the service that sends events. The SDK adds the plan and source information to every event that doesn't set its own. setPlan() requires 1.8.0 or later, and setIngestionMetadata() requires 1.11.0 or later.
client.setPlan(new Plan().setBranch("main").setVersion("3"));
client.setIngestionMetadata(new IngestionMetadata()
.setSourceName("billing-service")
.setSourceVersion("2.1.0"));
client.logEvent(new Event("Invoice Paid", "user-12345"));
Logging
By default, the SDK logs only errors, to standard error. To change the level, call setLogMode(). Go to Turn on debug logging.
To send SDK messages to your logging framework, extend AmplitudeLog and override log(). Compare levels with getLogLevel(), because the level fields are private. Requires 1.10.0 or later. getLogMode() and getLogLevel() require 1.12.0 or later.
class AppLogger extends AmplitudeLog {
@Override
public void log(String tag, String message, LogMode messageMode) {
if (messageMode.getLogLevel() >= getLogMode().getLogLevel()) {
System.out.println("[amplitude] " + messageMode + " " + tag + ": " + message);
}
}
}
client.setLogger(new AppLogger());
client.setLogMode(AmplitudeLog.LogMode.DEBUG);
client.logEvent(new Event("Button Clicked", "user-12345"));
Call setLogMode() after setLogger(). The new logger starts at ERROR, whatever level the old one had.
Was this helpful?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.