← Files TemporalARCHIVED FILE

skills/temporal-developer/references/java/java.md

11.5 KB · Nov 3, 2026 · 18:19 UTC

↓ Download file

See the change to this file →

# Temporal Java SDK Reference

## Overview

The Temporal Java SDK (`io.temporal:temporal-sdk`) uses an interface + implementation pattern for both Workflows and Activities. Java 8+ required; Java 21+ strongly recommended for virtual thread support.

## Quick Start

**Add Dependencies:**

Gradle:

```groovy
implementation 'io.temporal:temporal-sdk:1.+'
implementation 'io.temporal:temporal-envconfig:1.+'
```

Maven:

```xml
<dependency>
    <groupId>io.temporal</groupId>
    <artifactId>temporal-sdk</artifactId>
    <version>[1.0,)</version>
</dependency>
<dependency>
    <groupId>io.temporal</groupId>
    <artifactId>temporal-envconfig</artifactId>
    <version>[1.0,)</version>
</dependency>
```

**GreetingInput.java** - Shared input class (the public no-argument constructor and fields support JSON conversion):

```java
package greetingapp;

public class GreetingInput {
    public String firstName;
    public String lastName;

    public GreetingInput() {}

    public GreetingInput(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
```

**GreetActivities.java** - Activity interface:

```java
package greetingapp;

import io.temporal.activity.ActivityInterface;
import io.temporal.activity.ActivityMethod;

@ActivityInterface
public interface GreetActivities {

    @ActivityMethod
    String greet(GreetingInput input);
}
```

**GreetActivitiesImpl.java** - Activity implementation:

```java
package greetingapp;

public class GreetActivitiesImpl implements GreetActivities {

    @Override
    public String greet(GreetingInput input) {
        return "Hello, " + input.firstName + " " + input.lastName + "!";
    }
}
```

**GreetingWorkflow.java** - Workflow interface:

```java
package greetingapp;

import io.temporal.workflow.WorkflowInterface;
import io.temporal.workflow.WorkflowMethod;

@WorkflowInterface
public interface GreetingWorkflow {

    @WorkflowMethod
    String greet(GreetingInput input);
}
```

**GreetingWorkflowImpl.java** - Workflow implementation:

```java
package greetingapp;

import io.temporal.activity.ActivityOptions;
import io.temporal.workflow.Workflow;

import java.time.Duration;

public class GreetingWorkflowImpl implements GreetingWorkflow {

    private final GreetActivities activities = Workflow.newActivityStub(
        GreetActivities.class,
        ActivityOptions.newBuilder()
            .setStartToCloseTimeout(Duration.ofSeconds(30))
            .build()
    );

    @Override
    public String greet(GreetingInput input) {
        return activities.greet(input);
    }
}
```

**GreetingWorker.java** - Worker setup (registers activity and workflow, runs indefinitely and processes tasks):

```java
package greetingapp;

import io.temporal.client.WorkflowClient;
import io.temporal.envconfig.ClientConfigProfile;
import io.temporal.serviceclient.WorkflowServiceStubs;
import io.temporal.worker.Worker;
import io.temporal.worker.WorkerFactory;

public class GreetingWorker {

    public static void main(String[] args) throws Exception {
        ClientConfigProfile profile = ClientConfigProfile.load();
        WorkflowServiceStubs service =
            WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions());
        WorkflowClient client =
            WorkflowClient.newInstance(service, profile.toWorkflowClientOptions());

        // Create factory and worker
        WorkerFactory factory = WorkerFactory.newInstance(client);
        Worker worker = factory.newWorker("greeting-queue");

        // Register workflow and activity implementations
        worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class);
        worker.registerActivitiesImplementations(new GreetActivitiesImpl());

        // Start polling
        factory.start();
    }
}
```

**Start the dev server:** Start `temporal server start-dev` in the background.

**Start the worker:** Run `GreetingWorker.main()` (e.g., `./gradlew run` or `mvn compile exec:java -Dexec.mainClass="greetingapp.GreetingWorker"`).

**Starter.java** - Start a workflow execution:

```java
package greetingapp;

import io.temporal.client.WorkflowClient;
import io.temporal.client.WorkflowOptions;
import io.temporal.envconfig.ClientConfigProfile;
import io.temporal.serviceclient.WorkflowServiceStubs;

import java.util.UUID;

public class Starter {

    public static void main(String[] args) throws Exception {
        ClientConfigProfile profile = ClientConfigProfile.load();
        WorkflowServiceStubs service =
            WorkflowServiceStubs.newServiceStubs(profile.toWorkflowServiceStubsOptions());
        WorkflowClient client =
            WorkflowClient.newInstance(service, profile.toWorkflowClientOptions());

        GreetingWorkflow workflow = client.newWorkflowStub(
            GreetingWorkflow.class,
            WorkflowOptions.newBuilder()
                .setWorkflowId(UUID.randomUUID().toString())
                .setTaskQueue("greeting-queue")
                .build()
        );

        String result = workflow.greet(new GreetingInput("Ada", "Lovelace"));
        System.out.println("Result: " + result);
    }
}
```

**Run the workflow:** Run `Starter.main()`. Should output: `Result: Hello, Ada Lovelace!`.

## Key Concepts

### Workflow Definition

- Annotate interface with `@WorkflowInterface`
- Put any state initialization logic in the workflow constructor to guarantee that it happens before signals/updates arrive. If your state initialization logic requires the workflow parameters, then add the `@WorkflowInit` decorator and parameters to your constructor.
- Annotate entry point method with `@WorkflowMethod` (exactly one per interface)
- Use `@SignalMethod` for signal handlers
- Use `@QueryMethod` for query handlers
- Use `@UpdateMethod` for update handlers
- Implementation class implements the interface

### Activity Definition

- Annotate interface with `@ActivityInterface`
- Optionally annotate methods with `@ActivityMethod` (for custom names)
- Implementation class can throw any exception
- Call from workflow via `Workflow.newActivityStub()`

### Evolving Inputs and Results

Prefer one serializable request record or class for Workflow and Activity inputs that may grow, and a response type for results that may grow. Handle missing new fields with compatible defaults; changing an existing primitive input to an object requires a migration because old payloads remain in history. See Temporal's [Java message-passing guide](https://docs.temporal.io/develop/java/workflows/message-passing#writing-message-handlers) for the same single-class recommendation.

### Worker Setup

- Load connection settings with `ClientConfigProfile.load()` and use the profile to configure both service stubs and the client
- `WorkflowServiceStubs` -- gRPC connection to Temporal Server
- `WorkflowClient` -- client used by worker to communicate with server
- `WorkerFactory` -- creates Worker instances
- `Worker` -- polls a single Task Queue, register workflows and activities on it
- Call `factory.start()` to begin polling

For Spring Boot apps, `temporal-spring-boot-starter` handles all of the above automatically via auto-configuration. See [Spring Boot Java integration guide](integrations/spring-boot.md).

## File Organization Best Practice

**Keep Workflow and Activity definitions in separate files.** Separating them is good practice for clarity and maintainability.

```
greetingapp/
├── GreetingInput.java          # Shared input class
├── GreetActivities.java        # Activity interface
├── GreetActivitiesImpl.java    # Activity implementation
├── GreetingWorkflow.java       # Workflow interface
├── GreetingWorkflowImpl.java   # Workflow implementation
├── GreetingWorker.java         # Worker setup
└── Starter.java                # Client code to start workflows
```

## Determinism Rules

The Java SDK has **no sandbox**. The developer is fully responsible for writing deterministic workflow code. All non-deterministic operations must happen in Activities.

**Do not use in workflow code:**

- `Thread` / `new Thread()` -- use `Workflow.newTimer()` or `Async.function()`
- `synchronized` / `Lock` -- workflow code is single-threaded
- `UUID.randomUUID()` -- use `Workflow.randomUUID()`
- `Math.random()` -- use `Workflow.newRandom()`
- `System.currentTimeMillis()` / `Instant.now()` -- use `Workflow.currentTimeMillis()`
- File I/O, network calls, database access -- use Activities
- `Thread.sleep()` -- use `Workflow.sleep()`
- Mutable static fields -- workflow instances must not share state

**Use `Workflow.*` APIs instead:**

- `Workflow.sleep()` for timers
- `Workflow.currentTimeMillis()` for current time
- `Workflow.randomUUID()` for UUIDs
- `Workflow.newRandom()` for random numbers
- `Workflow.getLogger()` for replay-safe logging

See [Temporal determinism rules](../core/determinism.md) for detailed determinism rules.

## Common Pitfalls

1. **Non-deterministic code in workflows** - Use `Workflow.*` APIs instead of standard Java APIs; perform I/O in Activities
2. **Forgetting `@WorkflowInterface` or `@ActivityInterface`** - Annotations are required on interfaces for registration
3. **Multiple `@WorkflowMethod` on one interface** - Only one `@WorkflowMethod` is allowed per `@WorkflowInterface`
4. **Using `Thread.sleep()` in workflows** - Use `Workflow.sleep()` for deterministic timers
5. **Forgetting to heartbeat** - Long-running activities need `Activity.getExecutionContext().heartbeat()`
6. **Using `System.out.println()` in workflows** - Use `Workflow.getLogger()` for replay-safe logging
7. **Not registering activities as instances** - `registerActivitiesImplementations()` takes object instances (`new MyActivitiesImpl()`), not classes
8. **Blocking the workflow thread** - Never perform I/O or long computations in workflow code; use Activities
9. **Sharing mutable state between workflow instances** - Each workflow execution must be independent

## Writing Tests

See [Java testing guide](testing.md) for info on writing tests.

## Additional Resources

### Reference Files

- **[Java workflow patterns](patterns.md)** - Signals, queries, child workflows, saga pattern, etc.
- **[Java determinism rules](determinism.md)** - Determinism rules and safe alternatives for Java
- **[Java common pitfalls](gotchas.md)** - Java-specific mistakes and anti-patterns
- **[Java error handling guide](error-handling.md)** - ApplicationFailure, retry policies, non-retryable errors
- **[Java observability guide](observability.md)** - Logging, metrics, tracing, Search Attributes
- **[Java testing guide](testing.md)** - TestWorkflowEnvironment, time-skipping, activity mocking
- **[Java advanced features guide](advanced-features.md)** - Schedules, worker tuning, and more
- **[Java data handling guide](data-handling.md)** - Data converters, Jackson, payload encryption
- **[Java versioning guide](versioning.md)** - Patching API, workflow type versioning, Worker Versioning
- **[Java standalone Activities guide](standalone-activities.md)** - Standalone Activities: run an Activity directly from a Client without a Workflow. Concept overview at [Temporal standalone Activities guide](../core/standalone-activities.md).
- **[Java Task Queue priority and fairness guide](priority-fairness.md)** - Task Queue Priority and Fairness SDK options and examples. Concept overview at [Temporal Task Queue priority and fairness guide](../core/priority-fairness.md).

### Java Integrations

For Java-specific third-party integrations (Spring Boot, Spring AI, etc.), see [integrations catalog](../integrations.md) and filter for Java. Reference files live under `references/java/integrations/`.

SHA-256: 5aa212854187844b6a5954e99f3d9c2aaeadcb7ba877328bce8e39ab077b089a