Skip to content

temporalio/samples-java

Repository files navigation

Temporal Java SDK Samples

This repository contains samples that demonstrate various capabilities of Temporal using the Java SDK.

It contains the following modules:

  • Core: showcases many different SDK features.
  • SpringBoot: showcases SpringBoot autoconfig integration.
  • SpringBoot Basic: Minimal sample showing SpringBoot autoconfig integration without any extra external dependencies.
  • Spring AI: demonstrates the Temporal Spring AI integration — durable AI agents with chat models, tools, MCP servers, vector stores, and embeddings.

Learn more about Temporal and Java SDK

Requirements

  • Java 17+
  • Local Temporal Server, easiest to get started would be using Temporal CLI. For more options see docs here.

Build and run tests

  1. Clone this repository:

    git clone https://github.com/temporalio/samples-java
    cd samples-java
    
  2. Build and run Tests

    ./gradlew build
    

Running Samples:

You can run both "Core" and "SpringBoot" samples from the main samples project directory. Details on how to run each sample can be found in following two sections. To skip to SpringBoot samples click here.

Running "Core" samples

See the README.md file in each main sample directory for cut/paste Gradle command to run specific example.

Hello samples

  • Hello: This sample includes a number of individual Workflows that can be executed independently. Each one demonstrates something specific.

    • HelloAccumulator: Demonstrates a Workflow Definition that accumulates signals and continues as new.
    • HelloActivity: Demonstrates a Workflow Definition that executes a single Activity.
    • HelloActivityRetry: Demonstrates how to Retry an Activity Execution.
    • HelloActivityExclusiveChoice: Demonstrates how to execute Activities based on dynamic input.
    • HelloAsync: Demonstrates how to execute Activities asynchronously and wait for them using Promises.
    • HelloAwait: Demonstrates how to use Await statement to wait for a condition.
    • HelloParallelActivity: Demonstrates how to execute multiple Activities in parallel, asynchronously, and wait for them using Promise.allOf.
    • HelloAsyncActivityCompletion: Demonstrates how to complete an Activity Execution asynchronously.
    • HelloAsyncLambda: Demonstrates how to execute part of a Workflow asynchronously in a separate task (thread).
    • HelloCancellationScope: Demonstrates how to explicitly cancel parts of a Workflow Execution.
    • HelloCancellationScopeWithTimer: Demonstrates how to cancel activity when workflow timer fires and complete execution. This can prefered over using workflow run/execution timeouts.
    • HelloDetachedCancellationScope: Demonstrates how to execute cleanup code after a Workflow Execution has been explicitly cancelled.
    • HelloChild: Demonstrates how to execute a simple Child Workflow.
    • HelloCron: Demonstrates how to execute a Workflow according to a cron schedule.
    • HelloDynamic: Demonstrates how to use DynamicWorkflow and DynamicActivity interfaces.
    • HelloEagerWorkflowStart: Demonstrates the use of a eager workflow start.
    • HelloPeriodic: Demonstrates the use of the Continue-As-New feature.
    • HelloException: Demonstrates how to handle exception propagation and wrapping.
    • HelloLocalActivity: Demonstrates the use of a Local Activity.
    • HelloPolymorphicActivity: Demonstrates Activity Definitions that extend a common interface.
    • HelloQuery: Demonstrates how to Query the state of a Workflow Execution.
    • HelloSchedules: Demonstrates how to create and interact with a Schedule.
    • HelloSignal: Demonstrates how to send and handle a Signal.
    • HelloSaga: Demonstrates how to use the SAGA feature.
    • HelloSearchAttributes: Demonstrates how to add custom Search Attributes to Workflow Executions.
    • HelloSideEffect**: Demonstrates how to implement a Side Effect.
    • HelloUpdate: Demonstrates how to create and interact with an Update.
    • HelloDelayedStart: Demonstrates how to use delayed start config option when starting a Workflow Executions.
    • HelloSignalWithTimer: Demonstrates how to use collect signals for certain amount of time and then process last one.
    • HelloWorkflowTimer: Demonstrates how we can use workflow timer to restrict duration of workflow execution instead of workflow run/execution timeouts.
    • Auto-Heartbeating: Demonstrates use of Auto-heartbeating utility via activity interceptor.
    • HelloSignalWithStartAndWorkflowInit: Demonstrates how WorkflowInit can be useful with SignalWithStart to initialize workflow variables.
    • HelloStandaloneActivity: Demonstrates how to execute a Standalone Activity directly from an ActivityClient, without a Workflow.

Scenario-based samples

  • File Processing Sample: Demonstrates how to route tasks to specific Workers. This sample has a set of Activities that download a file, processes it, and uploads the result to a destination. Any Worker can execute the first Activity. However, the second and third Activities must be executed on the same host as the first one.

  • Booking SAGA: Demonstrates Temporals take on the Camunda BPMN "trip booking" example.

  • Synchronous Booking SAGA: Demonstrates low latency SAGA with potentially long compensations.

  • Money Transfer: Demonstrates the use of a dedicated Activity Worker.

  • Money Batch: Demonstrates a situation where a single deposit should be initiated for multiple withdrawals. For example, a seller might want to be paid once per fixed number of transactions. This sample can be easily extended to perform a payment based on more complex criteria, such as at a specific time or an accumulated amount. The sample also demonstrates how to Signal the Workflow when it executes (Signal with start). If the Workflow is already executing, it just receives the Signal. If it is not executing, then the Workflow executes first, and then the Signal is delivered to it. Signal with start is a "lazy" way to execute Workflows when Signaling them.

  • Domain-Specific-Language - Define sequence of steps in JSON: Demonstrates using domain specific language (DSL) defined in JSON to specify sequence of steps to be performed in our workflow.

  • Polling Services: Recommended implementation of an activity that needs to periodically poll an external resource waiting its successful completion

  • Heartbeating Activity Batch: Batch job implementation using a heartbeating activity.

  • Iterator Batch: Batch job implementation using the workflow iterator pattern.

  • Sliding Window Batch: A batch implementation that maintains a configured number of child workflows during processing.

  • Safe Message Passing: Safely handling concurrent updates and signals messages.

  • Custom Annotation: Demonstrates how to create a custom annotation using an interceptor.

  • Async Packet Delivery: Demonstrates running multiple execution paths async within single execution.

  • Worker Versioning: Demonstrates how to use worker versioning to manage workflow code changes.

  • Environment Configuration: Load client configuration from TOML files with programmatic overrides.

API demonstrations

SDK Metrics

Tracing Support

Encryption Support

  • Encrypted Payloads: Demonstrates how to use simple codec to encrypt and decrypt payloads.

  • AWS Encryption SDK: Demonstrates how to use the AWS Encryption SDK to encrypt and decrypt payloads with AWS KMS.

Nexus Samples

  • Getting Started: Demonstrates how to get started with Temporal and Nexus.

  • Mapping Multiple Arguments: Demonstrates how map a Nexus operation to a Workflow that takes multiple arguments.

  • Cancellation: Demonstrates how to cancel an async Nexus operation.

  • Context/Header Propagation: Demonstrates how to propagate context through Nexus operation headers.

  • Nexus Messaging: Demonstrates how to send signal, update and query messages through Nexus. This contains two samples, one sending messages to an existing workflow and a second that creates a workflow through Nexus and sends messages to it.

Running SpringBoot Samples

These samples use SpringBoot 2 by default. To switch to using SpringBoot 3 look at the gradle.properties file and follow simple instructions there.

  1. Start SpringBoot from main repo dir:

    ./gradlew :springboot:bootRun
    

To run the basic sample run

   ./gradlew :springboot-basic:bootRun
  1. Navigate to localhost:3030

  2. Select which sample you want to run

More info on each sample:

  • Hello: Invoke simple "Hello" workflow from a GET endpoint
  • SDK Metrics: Learn how to set up SDK Metrics
  • Synchronous Update: Learn how to use Synchronous Update feature with this purchase sample
  • Kafka Request / Reply: Sample showing possible integration with event streaming platforms such as Kafka
  • Customize Options: Sample showing how to customize options such as WorkerOptions, WorkerFactoryOptions, etc (see options config here)
  • Apache Camel Route: Sample showing how to start Workflow execution from a Camel Route
  • Custom Actuator Endpoint: Sample showing how to create a custom Actuator endpoint that shows registered Workflow and Activity impls per task queue.

Temporal Cloud

To run any of the SpringBoot samples in your Temporal Cloud namespace:

  1. Edit the application-tc.yaml to set your namespace and client certificates.

  2. Start SpringBoot from main repo dir with the tc profile:

    ./gradlew bootRun --args='--spring.profiles.active=tc'
    
  3. Follow the previous section from step 2

Running Spring AI Samples

The Spring AI samples demonstrate the Temporal Spring AI integration, which makes Spring AI agents durable on Temporal — model calls run as Temporal Activities recorded in Workflow history, and tools are dispatched per their type so they fit Workflow execution.

Each sample is its own Spring Boot application with an interactive CLI. Run from the main repo dir:

   ./gradlew :springai:basic:bootRun
   ./gradlew :springai:mcp:bootRun
   ./gradlew :springai:multimodel:bootRun
   ./gradlew :springai:rag:bootRun

All samples need an OPENAI_API_KEY environment variable; some need additional setup (see each sample's source for details).

More info on each sample:

  • Basic: Chat workflow with three tool flavors — activity-backed (WeatherActivity), plain workflow tools (StringTools), and @SideEffectTool (TimestampTools) — plus a PromptChatMemoryAdvisor for conversation history.
  • MCP: Connects to a Model Context Protocol server and exposes its tools to the AI through Temporal activities. Defaults to the filesystem MCP server.
  • Multi-Model: Two providers in one workflow (OpenAI and Anthropic), per-model ActivityOptions overrides via a Spring bean, plus a route that exercises Anthropic's extended-thinking mode through provider-specific ChatOptions pass-through. Requires ANTHROPIC_API_KEY in addition to OPENAI_API_KEY.
  • RAG: Vector store + embeddings for retrieval-augmented generation. Add documents, then ask questions; the workflow searches the vector store and grounds the answer in the retrieved context.

Packages

 
 
 

Contributors