* 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>
5.4 KiB
Java Gotchas
Java-specific mistakes and anti-patterns. See also Common Gotchas for language-agnostic concepts.
Non-Deterministic Operations
Critical: The Java SDK has NO sandbox. Unlike Python (which uses a sandbox) or TypeScript (which uses V8 isolation), the Java SDK relies entirely on developer conventions. Non-deterministic calls silently succeed during initial execution but cause NonDeterministicException on replay.
Forbidden in workflow code — use the Temporal Workflow.* equivalents instead:
Thread.sleep→Workflow.sleepUUID.randomUUID→Workflow.randomUUIDMath.random→Workflow.newRandomSystem.currentTimeMillis→Workflow.currentTimeMillisnew Thread→Async.functionsynchronizedblocks → unnecessary (workflow code runs under a global lock)
See references/java/determinism.md for the full table of forbidden operations, safe alternatives, and detailed examples.
Wrong Retry Classification
Example: Transient networks errors should be retried. Authentication errors should not be.
See references/java/error-handling.md to understand how to classify errors.
Heartbeating
Forgetting to Heartbeat Long Activities
// BAD - No heartbeat, can't detect stuck activities
@Override
public void processLargeFile(String path) {
for (String chunk : readChunks(path)) {
process(chunk); // Takes hours, no heartbeat
}
}
// GOOD - Regular heartbeats with progress
@Override
public void processLargeFile(String path) {
int i = 0;
for (String chunk : readChunks(path)) {
Activity.getExecutionContext().heartbeat("Processing chunk " + i++);
process(chunk);
}
}
Heartbeat Timeout Too Short
// BAD - Heartbeat timeout shorter than processing time
ActivityOptions options = ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofMinutes(30))
.setHeartbeatTimeout(Duration.ofSeconds(10)) // Too short!
.build();
// GOOD - Heartbeat timeout allows for processing variance
ActivityOptions options = ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofMinutes(30))
.setHeartbeatTimeout(Duration.ofMinutes(2))
.build();
Set heartbeat timeout as high as acceptable for your use case — each heartbeat counts as an action.
Cancellation
Not Handling Workflow Cancellation
// BAD - Cleanup doesn't run on cancellation
public class BadWorkflow implements MyWorkflow {
@Override
public void run() {
activities.acquireResource();
activities.doWork();
activities.releaseResource(); // Never runs if cancelled!
}
}
// GOOD - Use try/finally with CancellationScope.nonCancellable
import io.temporal.workflow.CancellationScope;
import io.temporal.workflow.Workflow;
public class GoodWorkflow implements MyWorkflow {
@Override
public void run() {
activities.acquireResource();
try {
activities.doWork();
} finally {
CancellationScope scope = Workflow.newDetachedCancellationScope(
() -> activities.releaseResource()
);
scope.run();
}
}
}
Not Handling Activity Cancellation
Activities must opt in to receive cancellation. This requires:
- Heartbeating - Cancellation is delivered via heartbeat
- Catching CanceledFailure - Thrown when heartbeat detects cancellation
// BAD - Activity ignores cancellation
@Override
public void longActivity() {
doExpensiveWork(); // Runs to completion even if cancelled
}
// GOOD - Heartbeat and catch cancellation
import io.temporal.activity.Activity;
import io.temporal.failure.CanceledFailure;
@Override
public void longActivity() {
try {
for (int i = 0; i < items.size(); i++) {
Activity.getExecutionContext().heartbeat(i);
process(items.get(i));
}
} catch (CanceledFailure e) {
cleanup();
throw e;
}
}
Testing
Not Testing Failures
It is important to make sure workflows work as expected under failure paths in addition to happy paths. Please see references/java/testing.md for more info.
Not Testing Replay
Replay tests help you test that you do not have hidden sources of non-determinism bugs in your workflow code, and should be considered in addition to standard testing. This is especially critical in Java since there is no sandbox. Please see references/java/testing.md for more info.
Timers and Sleep
Using Thread.sleep
// BAD - Thread.sleep is not deterministic during replay
public class BadWorkflow implements MyWorkflow {
@Override
public void run() {
try {
Thread.sleep(60000); // Non-deterministic!
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// GOOD - Use Workflow.sleep for deterministic timers
import io.temporal.workflow.Workflow;
import java.time.Duration;
public class GoodWorkflow implements MyWorkflow {
@Override
public void run() {
Workflow.sleep(Duration.ofSeconds(60)); // Deterministic
}
}
Why this matters: Thread.sleep uses the system clock, which differs between original execution and replay. Workflow.sleep creates a durable timer in the event history, ensuring consistent behavior during replay. Unlike Python and TypeScript, there is no sandbox to catch this — the call silently succeeds and only fails on replay.