# Run a Worker

> For the complete documentation index, see [llms.txt](https://docs.temporal.io/llms.txt).
> Any documentation page is available as raw Markdown by appending `.md` to its URL.
> For related questions, query https://docs.temporal.io/api/retrieve?q=<question>&jtb=<job-to-be-done>&src=md-page&agent=<your-name> (no auth; returns JSON `{content, source_url, page_url}`, with `source_url` pointing to Markdown for docs pages). Don't include personal data or credentials.

> Create and run a Temporal Worker using the Java SDK.

This page covers long-lived Workers that you host and run as persistent processes.
For Workers that run on serverless compute like AWS Lambda, see [Serverless Workers](/develop/java/workers/serverless-workers).

## Create and run a Worker 

Create a [`WorkerFactory`](https://www.javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/worker/WorkerFactory.html) from a [Temporal Client](/develop/java/client/temporal-client), then call `newWorker()` with the Task Queue to poll.
Register the Workflow and Activity types the Worker can execute, then call `start()` on the factory.

<!--SNIPSTART java-create-worker-->
[features/snippets/worker/worker.java](https://github.com/temporalio/features/blob/main/features/snippets/worker/worker.java)
```java
WorkerFactory factory = WorkerFactory.newInstance(client);

Worker worker = factory.newWorker("my-task-queue");
worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class);
worker.registerActivitiesImplementations(new GreetingActivitiesImpl());

factory.start();
```
<!--SNIPEND-->

`start()` starts every Worker the factory created, so one factory can run several Workers in a single process.
The call returns immediately and the Workers poll on background threads, so the process has to stay alive.

## Register Workflows and Activities 

All Workers polling the same Task Queue must register the same Workflow Types and Activity Types.
A Task Queue does not route by type, so any Worker polling it can receive any Task on that queue.
A Worker that receives a Task for a type it did not register fails that Task.

Register Workflows by class with `registerWorkflowImplementationTypes()`.
The Worker creates a new instance for each Workflow Execution, so a Workflow Type can be registered only once per Worker.
Registering two implementations of the same type throws at registration time.

Register Activities by instance with `registerActivitiesImplementations()`.
One instance serves every Workflow Execution that calls it, so the implementation must be thread-safe.
Pass dependencies such as database clients through the constructor.

```java
worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class, OrderWorkflowImpl.class);
worker.registerActivitiesImplementations(new GreetingActivitiesImpl(databaseClient));
```

A Worker can register one implementation of [`DynamicWorkflow`](https://www.javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/workflow/DynamicWorkflow.html) and one of `DynamicActivity` alongside any number of type-specific implementations.
The dynamic implementation handles Workflow and Activity Types that no registered type matches.

## Connect to Temporal Cloud 

To run a Worker against Temporal Cloud, configure the Client connection with your Namespace address and authentication credentials.
See [Connect to Temporal Cloud](/develop/java/client/temporal-client#connect-to-temporal-cloud) for setup instructions.

## Configure Worker options 

Pass [`WorkerOptions`](https://www.javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/worker/WorkerOptions.html) to `newWorker()` to set concurrency limits, poller counts, and rate limits for a single Worker.
Pass [`WorkerFactoryOptions`](https://www.javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/worker/WorkerFactoryOptions.html) to `newInstance()` for settings shared by every Worker in the process, such as the Workflow cache size.
The defaults work for most cases.

To tune these values against real load, see [Worker performance](/develop/worker-performance) and the [Worker tuning reference](/develop/worker-tuning-reference).

## Run a versioned Worker 

Set a Worker Deployment Version and enable versioning in `WorkerOptions`, then set a versioning behavior on each Workflow.

<!--SNIPSTART java-versioned-worker-->
[features/snippets/worker/worker.java](https://github.com/temporalio/features/blob/main/features/snippets/worker/worker.java)
```java
WorkerOptions options =
    WorkerOptions.newBuilder()
        .setDeploymentOptions(
            WorkerDeploymentOptions.newBuilder()
                .setVersion(new WorkerDeploymentVersion("my-app", "1.0"))
                .setUseVersioning(true)
                .build())
        .build();

Worker worker = factory.newWorker("my-task-queue", options);
worker.registerWorkflowImplementationTypes(VersionedGreetingWorkflowImpl.class);
worker.registerActivitiesImplementations(new GreetingActivitiesImpl());
```
<!--SNIPEND-->

Annotate the Workflow method with `@WorkflowVersioningBehavior(VersioningBehavior.PINNED)` or `AUTO_UPGRADE`, or set a default for the whole Worker with `setDefaultVersioningBehavior()`.
The annotation belongs on the implementation, not the interface.

A versioning behavior applies only to a Worker that has versioning enabled.
If a Workflow declares one and its Worker does not enable versioning, the server rejects the Workflow Task and the Task retries instead of failing outright.

See [Worker Versioning](/worker-versioning) for the available versioning behaviors and how new versions roll out.

## Shut down a Worker 

Call `shutdown()` on the factory to stop polling for new Tasks, then `awaitTermination()` to give in-flight Tasks time to finish.

<!--SNIPSTART java-worker-graceful-shutdown-->
[features/snippets/worker/worker.java](https://github.com/temporalio/features/blob/main/features/snippets/worker/worker.java)
```java
factory.shutdown();
factory.awaitTermination(30, TimeUnit.SECONDS);
```
<!--SNIPEND-->

Both calls apply to every Worker the factory created.
See [Worker shutdown](/encyclopedia/workers/worker-shutdown) for what happens to in-flight Workflow Tasks and Activities.

### Heartbeat during shutdown 

By default, after you call `shutdown()`, an Activity that calls `Activity.getExecutionContext().heartbeat()` doesn't send a Heartbeat.
The call throws `ActivityWorkerShutdownException` instead.
An Activity can catch this exception to detect that the Worker is shutting down.
An Activity that ignores the exception keeps running, but the Temporal Service stops receiving its Heartbeats and can time it out with a [Heartbeat Timeout](/encyclopedia/detecting-activity-failures#heartbeat-timeout) before it finishes.

To let Activities keep sending Heartbeats while the Worker drains, set `setAllowActivityHeartbeatDuringShutdown(true)` on the Worker options.
This matches the behavior of the other Temporal SDKs.

<!--SNIPSTART java-worker-heartbeat-during-shutdown-->
[java-sandbox/worker-shutdown/src/main/java/io/temporal/docs/workershutdown/HeartbeatDuringShutdownExamples.java](https://github.com/temporalio/documentation-sdk-code-examples/blob/main/java-sandbox/worker-shutdown/src/main/java/io/temporal/docs/workershutdown/HeartbeatDuringShutdownExamples.java)
```java
WorkerOptions options =
    WorkerOptions.newBuilder().setAllowActivityHeartbeatDuringShutdown(true).build();
Worker worker = factory.newWorker("your-task-queue", options);
```
<!--SNIPEND-->

With this option enabled, `heartbeat()` no longer throws `ActivityWorkerShutdownException`, so an Activity can't use that exception to detect shutdown.
Each Activity must finish within the timeout you pass to `awaitTermination()`, or use another signal to detect shutdown.

The option has no effect on `shutdownNow()`, which attempts to stop running Activities by interrupting their threads. An Activity that ignores the interrupt may keep running.
`setAllowActivityHeartbeatDuringShutdown` is experimental and requires Java SDK v1.36.0 or later.
