Temporal Workflow Java SDK - A framework for authoring Workflows and Activities in Java
npx @tessl/cli install tessl/maven-io-temporal--temporal-sdk@1.31.00
# Temporal Java SDK
1
2
The Temporal Java SDK is a comprehensive framework for authoring reliable, scalable workflows and activities in Java. It provides type-safe APIs for building distributed applications that can withstand failures, handle retries, and manage complex business processes across multiple services and time scales.
3
4
## Package Information
5
6
- **Package Name**: temporal-sdk
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>io.temporal</groupId>
13
<artifactId>temporal-sdk</artifactId>
14
<version>1.31.0</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
// Workflow client and service interaction
22
import io.temporal.client.WorkflowClient;
23
import io.temporal.client.WorkflowOptions;
24
import io.temporal.servicestubs.WorkflowServiceStubs;
25
26
// Workflow implementation
27
import io.temporal.workflow.Workflow;
28
import io.temporal.workflow.WorkflowInterface;
29
import io.temporal.workflow.WorkflowMethod;
30
import io.temporal.workflow.SignalMethod;
31
import io.temporal.workflow.QueryMethod;
32
33
// Activity implementation
34
import io.temporal.activity.Activity;
35
import io.temporal.activity.ActivityInterface;
36
import io.temporal.activity.ActivityMethod;
37
import io.temporal.activity.ActivityOptions;
38
39
// Worker management
40
import io.temporal.worker.Worker;
41
import io.temporal.worker.WorkerFactory;
42
import io.temporal.worker.WorkerOptions;
43
44
// Common configurations and exceptions
45
import io.temporal.common.RetryOptions;
46
import io.temporal.failure.ApplicationFailure;
47
```
48
49
## Basic Usage
50
51
```java
52
// Define a workflow interface
53
@WorkflowInterface
54
public interface HelloWorkflow {
55
@WorkflowMethod
56
String sayHello(String name);
57
}
58
59
// Define an activity interface
60
@ActivityInterface
61
public interface HelloActivity {
62
@ActivityMethod
63
String getGreeting(String name);
64
}
65
66
// Implement the workflow
67
public class HelloWorkflowImpl implements HelloWorkflow {
68
private final HelloActivity activity = Workflow.newActivityStub(
69
HelloActivity.class,
70
ActivityOptions.newBuilder()
71
.setStartToCloseTimeout(Duration.ofSeconds(30))
72
.build()
73
);
74
75
@Override
76
public String sayHello(String name) {
77
return activity.getGreeting(name);
78
}
79
}
80
81
// Implement the activity
82
public class HelloActivityImpl implements HelloActivity {
83
@Override
84
public String getGreeting(String name) {
85
return "Hello, " + name + "!";
86
}
87
}
88
89
// Start a workflow
90
public class Main {
91
public static void main(String[] args) {
92
// Create workflow client
93
WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs();
94
WorkflowClient client = WorkflowClient.newInstance(service);
95
96
// Create worker
97
WorkerFactory factory = WorkerFactory.newInstance(client);
98
Worker worker = factory.newWorker("hello-task-queue");
99
worker.registerWorkflowImplementationTypes(HelloWorkflowImpl.class);
100
worker.registerActivitiesImplementations(new HelloActivityImpl());
101
102
// Start worker
103
factory.start();
104
105
// Execute workflow
106
HelloWorkflow workflow = client.newWorkflowStub(
107
HelloWorkflow.class,
108
WorkflowOptions.newBuilder()
109
.setTaskQueue("hello-task-queue")
110
.setWorkflowId("hello-workflow")
111
.build()
112
);
113
114
String result = workflow.sayHello("World");
115
System.out.println(result); // "Hello, World!"
116
}
117
}
118
```
119
120
## Architecture
121
122
The Temporal Java SDK is built around several key components:
123
124
- **Workflow Client**: Central interface for starting workflows, managing executions, and interacting with the Temporal service
125
- **Workers**: Execute workflow and activity code, polling task queues for work
126
- **Workflow Implementation**: Contains business logic with deterministic execution guarantees
127
- **Activity Implementation**: Handles external service calls and non-deterministic operations
128
- **Type-Safe Stubs**: Generated proxies providing compile-time type safety for workflow and activity invocations
129
- **Failure Handling**: Comprehensive exception hierarchy for retry logic and error propagation
130
- **Data Conversion**: Pluggable serialization system for payload encoding and decoding
131
132
## Capabilities
133
134
### Activity Execution
135
136
Comprehensive APIs for implementing activities that handle external service calls, with built-in retry logic, heartbeat support, and async completion patterns.
137
138
```java { .api }
139
// Core activity execution context
140
public final class Activity {
141
public static ActivityExecutionContext getExecutionContext();
142
public static RuntimeException wrap(Throwable e);
143
}
144
145
// Activity execution context with heartbeat and async completion
146
public interface ActivityExecutionContext {
147
ActivityInfo getInfo();
148
<V> void heartbeat(V details) throws ActivityCompletionException;
149
<V> Optional<V> getHeartbeatDetails(Class<V> detailsClass);
150
ManualActivityCompletionClient useLocalManualCompletion();
151
void doNotCompleteOnReturn();
152
}
153
154
// Activity configuration options
155
public final class ActivityOptions {
156
public static ActivityOptions.Builder newBuilder();
157
// Builder methods for timeouts, retry options, task queue, etc.
158
}
159
```
160
161
[Activity Execution and Configuration](./activities.md)
162
163
### Workflow Implementation
164
165
APIs for implementing workflow logic with deterministic execution, including timers, signals, queries, updates, and child workflows.
166
167
```java { .api }
168
// Central workflow utility class
169
public final class Workflow {
170
public static <T> T newActivityStub(Class<T> activityInterface, ActivityOptions options);
171
public static <T> T newLocalActivityStub(Class<T> activityInterface, LocalActivityOptions options);
172
public static <T> ChildWorkflowStub newChildWorkflowStub(Class<T> workflowInterface, ChildWorkflowOptions options);
173
public static void sleep(Duration duration);
174
public static long currentTimeMillis();
175
public static Random newRandom();
176
public static void continueAsNew(Object... args);
177
}
178
179
// Workflow interface annotations
180
@WorkflowInterface
181
@WorkflowMethod
182
@SignalMethod
183
@QueryMethod
184
@UpdateMethod
185
```
186
187
[Workflow Implementation and Lifecycle](./workflows.md)
188
189
### Service Interaction
190
191
Complete client APIs for workflow lifecycle management, including starting workflows, sending signals, executing queries and updates, and batch operations.
192
193
```java { .api }
194
// Primary workflow client interface
195
public interface WorkflowClient {
196
// Factory methods
197
public static WorkflowClient newInstance(WorkflowServiceStubs service);
198
public static WorkflowClient newInstance(WorkflowServiceStubs service, WorkflowClientOptions options);
199
200
// Workflow stub creation
201
public <T> T newWorkflowStub(Class<T> workflowInterface, WorkflowOptions options);
202
public <T> T newWorkflowStub(Class<T> workflowInterface, String workflowId);
203
public WorkflowStub newUntypedWorkflowStub(String workflowType, WorkflowOptions options);
204
205
// Static execution methods
206
public static WorkflowExecution start(Func<R> workflow);
207
public static <R> CompletableFuture<R> execute(Func<R> workflow);
208
}
209
210
// Workflow configuration options
211
public final class WorkflowOptions {
212
public static WorkflowOptions.Builder newBuilder();
213
// Builder methods for timeouts, retry options, task queue, etc.
214
}
215
```
216
217
[WorkflowClient and Service Interaction](./client.md)
218
219
### Worker Management
220
221
APIs for configuring and managing Temporal workers that execute workflow and activity code, with options for concurrency, task routing, and performance tuning.
222
223
```java { .api }
224
// Worker factory for creating and managing workers
225
public interface WorkerFactory {
226
public static WorkerFactory newInstance(WorkflowClient workflowClient);
227
public Worker newWorker(String taskQueue);
228
public Worker newWorker(String taskQueue, WorkerOptions options);
229
public void start();
230
public void shutdown();
231
public void awaitTermination(long timeout, TimeUnit unit);
232
}
233
234
// Individual worker for executing workflows and activities
235
public interface Worker {
236
public void registerWorkflowImplementationTypes(Class<?>... workflowImplementationClasses);
237
public void registerActivitiesImplementations(Object... activityImplementations);
238
public <R> void addWorkflowImplementationFactory(Class<R> workflowInterface, Func<R> factory);
239
}
240
241
// Worker configuration options
242
public final class WorkerOptions {
243
public static WorkerOptions.Builder newBuilder();
244
// Builder methods for concurrency limits, timeouts, tuning options
245
}
246
```
247
248
[Worker Configuration and Management](./workers.md)
249
250
### Exception Handling
251
252
Comprehensive exception hierarchy for handling workflow and activity failures, with support for retries, timeouts, cancellation, and custom application failures.
253
254
```java { .api }
255
// Base exception hierarchy
256
public class TemporalException extends RuntimeException { }
257
public class TemporalFailure extends TemporalException { }
258
259
// Specific failure types
260
public final class ActivityFailure extends TemporalFailure { }
261
public final class ApplicationFailure extends TemporalFailure {
262
public static ApplicationFailure newFailure(String message, String type);
263
public static ApplicationFailure newNonRetryableFailure(String message, String type);
264
}
265
public final class CanceledFailure extends TemporalFailure { }
266
public final class ChildWorkflowFailure extends TemporalFailure { }
267
public final class TimeoutFailure extends TemporalFailure { }
268
public final class TerminatedFailure extends TemporalFailure { }
269
```
270
271
[Exception Hierarchy and Error Handling](./exceptions.md)
272
273
### Data Conversion
274
275
Pluggable payload conversion system for serializing workflow arguments, results, and signals with support for custom codecs and encryption.
276
277
```java { .api }
278
// Core payload conversion interface
279
public interface PayloadConverter {
280
public Optional<Payload> toData(Object value) throws DataConverterException;
281
public <T> T fromData(Payload content, Class<T> valueClass, Type valueType) throws DataConverterException;
282
}
283
284
// Payload codec for encoding/decoding (encryption, compression)
285
public interface PayloadCodec {
286
public List<Payload> encode(List<Payload> payloads);
287
public List<Payload> decode(List<Payload> payloads);
288
}
289
290
// Serialization context for activities
291
public interface ActivitySerializationContext extends SerializationContext {
292
public String getNamespace();
293
public String getTaskQueue();
294
public String getWorkflowId();
295
}
296
```
297
298
[Payload Conversion and Serialization](./data-conversion.md)