Files
Donald Pinckney 0c8586b4c2 Add Java SDK support (#42)
* Add Java SDK reference files (11 files)

Create complete Java reference documentation covering:
- java.md: Entry point with quick start tutorial, key concepts
- patterns.md: 17 patterns (signals, queries, updates, child workflows,
  saga, cancellation scopes, heartbeating, etc.)
- determinism.md: Safe alternatives table, forbidden operations
- determinism-protection.md: Convention-based enforcement (no sandbox)
- error-handling.md: ApplicationFailure, retry/timeout config
- gotchas.md: Non-deterministic operations, cancellation, heartbeating
- testing.md: TestWorkflowEnvironment, Mockito mocking, replay testing
- versioning.md: Workflow.getVersion(), worker versioning
- data-handling.md: Jackson, PayloadConverter, encryption, search attributes
- observability.md: SLF4J logging, Micrometer metrics
- advanced-features.md: Schedules, async completion, worker tuning

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix Java alignment issues from self-review

- Reduce gotchas.md Non-Deterministic Operations from ~94 lines to ~12
  (reference determinism.md instead of duplicating)
- Remove Workflow Failure Exception Types duplication from error-handling.md
  (keep only in advanced-features.md)
- Expand versioning.md Worker Versioning with Key Concepts, PINNED vs
  AUTO_UPGRADE, Deployment Strategies subsections
- Fix section names to match Python reference style:
  Activity Heartbeat Details, Handling Activity Errors,
  Retry Policy Configuration, Workflow Test Environment,
  Mocking Activities, Workflow Replay Testing
- Reduce data-handling.md Payload Encryption verbosity
- Reduce observability.md Logger Customization verbosity
- Reduce testing.md to single approach per section
- Rename determinism.md "Convention-Based Enforcement" to "SDK Protection"
- Fix handler guidance in patterns.md to match Python

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix correctness issues in Java reference files

- patterns.md: Fix Queries section — ActivityStub → typed interface
  (Workflow.newActivityStub returns the typed interface, not ActivityStub)
- data-handling.md: Add missing ProtobufPayloadConverter to default
  converter chain (4th of 5 converters)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add Java to SKILL.md and core/determinism.md

- SKILL.md: Add "Temporal Java" trigger phrase, update Overview to
  list Java, add Java entry to Getting Started references
- core/determinism.md: Add Java entry to SDK Protection Mechanisms
  (no sandbox, convention-based, NonDeterministicException at replay)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Apply manual editorial fixes to Java references

- java.md: Remove "Understanding Replay" section (covered by Overview),
  simplify File Organization note (no sandbox rationale)
- gotchas.md: Move Heartbeating before Cancellation, make Wrong Retry
  Classification brief with reference (not inline examples)
- error-handling.md: Remove editorializing from Workflow Failure note
- determinism-protection.md: Remove cross-language comparison paragraph
  (state Java's approach on its own terms)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add temporal-workflowcheck static analysis to Java determinism docs

- determinism-protection.md: Add "Static Analysis with temporal-workflowcheck"
  section with Gradle/Maven setup, manual run, and suppression instructions.
  Beta warning included.
- determinism.md: Update overview and SDK Protection to reference workflowcheck
- core/determinism.md: Update Java entry in SDK Protection Mechanisms

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Integrate feedback from Go PR into Java patterns

- Updates: Add validator note — validators must not mutate state or
  block (matches note added to Python, TypeScript, Go, and core)
- Saga Pattern: Use Workflow.newDetachedCancellationScope() for
  compensations so they execute even if the workflow is cancelled
  (mirrors Go's workflow.NewDisconnectedContext pattern)

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* docs: add @WorkflowInit description to java.md Key Concepts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* mark java as supported

* Apply suggestions from code review

Co-authored-by: Brian Strauch <brian@brianstrauch.com>

* strongly recommend java 21+

* Softened stance on static checker and replay testing.

* address python/typescript sandboxing comment

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Brian Strauch <brian.strauch@temporal.io>
Co-authored-by: Brian Strauch <brian@brianstrauch.com>
2026-04-02 17:07:33 -04:00

250 lines
8.7 KiB
Markdown

# 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.+'
```
Maven:
```xml
<dependency>
<groupId>io.temporal</groupId>
<artifactId>temporal-sdk</artifactId>
<version>[1.0,)</version>
</dependency>
```
**GreetActivities.java** - Activity interface:
```java
package greetingapp;
import io.temporal.activity.ActivityInterface;
import io.temporal.activity.ActivityMethod;
@ActivityInterface
public interface GreetActivities {
@ActivityMethod
String greet(String name);
}
```
**GreetActivitiesImpl.java** - Activity implementation:
```java
package greetingapp;
public class GreetActivitiesImpl implements GreetActivities {
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}
```
**GreetingWorkflow.java** - Workflow interface:
```java
package greetingapp;
import io.temporal.workflow.WorkflowInterface;
import io.temporal.workflow.WorkflowMethod;
@WorkflowInterface
public interface GreetingWorkflow {
@WorkflowMethod
String greet(String name);
}
```
**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(String name) {
return activities.greet(name);
}
}
```
**GreetingWorker.java** - Worker setup:
```java
package greetingapp;
import io.temporal.client.WorkflowClient;
import io.temporal.serviceclient.WorkflowServiceStubs;
import io.temporal.worker.Worker;
import io.temporal.worker.WorkerFactory;
public class GreetingWorker {
public static void main(String[] args) {
// Create gRPC stubs for local dev server (localhost:7233)
WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs();
// Create client
WorkflowClient client = WorkflowClient.newInstance(service);
// 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.serviceclient.WorkflowServiceStubs;
import java.util.UUID;
public class Starter {
public static void main(String[] args) {
WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs();
WorkflowClient client = WorkflowClient.newInstance(service);
GreetingWorkflow workflow = client.newWorkflowStub(
GreetingWorkflow.class,
WorkflowOptions.newBuilder()
.setWorkflowId(UUID.randomUUID().toString())
.setTaskQueue("greeting-queue")
.build()
);
String result = workflow.greet("my name");
System.out.println("Result: " + result);
}
}
```
**Run the workflow:** Run `Starter.main()`. Should output: `Result: Hello, my name!`.
## 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()`
### Worker Setup
- `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
## File Organization Best Practice
**Keep Workflow and Activity definitions in separate files.** Separating them is good practice for clarity and maintainability.
```
greetingapp/
├── 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 `references/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 `references/java/testing.md` for info on writing tests.
## Additional Resources
### Reference Files
- **`references/java/patterns.md`** - Signals, queries, child workflows, saga pattern, etc.
- **`references/java/determinism.md`** - Determinism rules and safe alternatives for Java
- **`references/java/gotchas.md`** - Java-specific mistakes and anti-patterns
- **`references/java/error-handling.md`** - ApplicationFailure, retry policies, non-retryable errors
- **`references/java/observability.md`** - Logging, metrics, tracing, Search Attributes
- **`references/java/testing.md`** - TestWorkflowEnvironment, time-skipping, activity mocking
- **`references/java/advanced-features.md`** - Schedules, worker tuning, and more
- **`references/java/data-handling.md`** - Data converters, Jackson, payload encryption
- **`references/java/versioning.md`** - Patching API, workflow type versioning, Worker Versioning