[[tasks_parallel_worker]]
= Developing Parallel Tasks using the Worker API

The Worker API provides the ability to break up the execution of a task action into discrete units of work and then to execute that work concurrently and asynchronously.
This allows Gradle to fully utilize the resources available and complete builds faster.
This section will walk you through the process of converting an existing custom task to use the Worker API.

This section assumes that you understand the basics of writing Gradle custom tasks.
For more information on that topic, consult the <<custom_tasks.adoc#custom_tasks,section on custom tasks>>.

You'll start by creating a custom task class that generates MD5 hashes for a configurable set of files.
Then, you'll convert this custom task to use the Worker API.
Then we'll explore running the task with different levels of isolation.
In the process, you'll learn about the basics of the Worker API and the capabilities it provides.

== Create a custom task class

First, you'll need to create a custom task that generates MD5 hashes of a configurable set of files.

In a new directory, create a `buildSrc/build.gradle(.kts)` file.

====
include::sample[dir="snippets/workerApi/md5CustomTask/kotlin",files="buildSrc/build.gradle.kts[]"]
include::sample[dir="snippets/workerApi/md5CustomTask/groovy",files="buildSrc/build.gradle[]"]
====
<1> Your custom task class will use https://commons.apache.org/proper/commons-codec/[Apache Commons Codec] to generate MD5 hashes.

TIP: If you are not familiar with `buildSrc`, this is a special directory that allows you to define and build custom classes that should be available for use in your build script.
See <<organizing_gradle_projects.adoc#sec:build_sources,the section on organizing build logic>> for further information.

Now, create a custom task class in your `buildSrc/src/main/java` directory.
You should name this class `CreateMD5`.

.buildSrc/src/main/java/CreateMD5.java
[source,java]
----
include::{snippetsPath}/workerApi/md5CustomTask/groovy/buildSrc/src/main/java/CreateMD5.java[]
----
<1> link:{javadocPath}/org/gradle/api/tasks/SourceTask.html[SourceTask] is a convenience type for tasks that operate on a set of source files.
<2> The output of the task will go into a configured directory.
<3> The task iterates over all of the files defined as "source files" and creates an MD5 hash of each.
<4> Insert an artificial sleep to simulate hashing a large file (the sample files won't be that large).
<5> The MD5 hash of each file is written to the output directory into a file of the same name with an "md5" extension.

Next, create a `build.gradle(.kts)` that registers your new `CreateMD5` task.

====
include::sample[dir="snippets/workerApi/md5CustomTask/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/workerApi/md5CustomTask/groovy",files="build.gradle[]"]
====
<1> Apply the `base` plugin so that you'll have a `clean` task to use to remove the output.
<2> MD5 hash files will be written to `build/md5`.
<3> This task will generate MD5 hash files for every file in the `src` directory.

Now, you'll need some source to generate MD5 hashes from.
Create 3 files in the src directory:

.src/einstein.txt
[source,text]
----
include::{snippetsPath}/workerApi/md5CustomTask/groovy/src/einstein.txt[]
----

.src/feynman.txt
[source,text]
----
include::{snippetsPath}/workerApi/md5CustomTask/groovy/src/feynman.txt[]
----

.src/oppenheimer.txt
[source,text]
----
include::{snippetsPath}/workerApi/md5CustomTask/groovy/src/oppenheimer.txt[]
----

At this point, you can give your task a try:

[listing]
----
$ gradle md5
----

You should see output similar to:

[listing]
----
include::{snippetsPath}/workerApi/md5CustomTask/tests/md5Task.out[]
----

In the `build/md5` directory, you should now see corresponding files with an `md5` extension containing MD5 hashes of the files from the `src` directory.
Notice that the task takes at least 9 seconds to run because it hashes each file one at a time (i.e. 3 files at ~3 seconds a piece).

[[converting_to_worker_api]]
== Converting to the Worker API

Although this task processes each file in sequence, the processing of each file is independent of any other file.
It would be really nice if this work was done in parallel and could take advantage of multiple processors.
This is where the Worker API can help.

First, you'll need to define an interface that represents the parameters of each unit of work and extends `org.gradle.workers.WorkParameters`.
For the generation of MD5 hash files, the unit of work will require two parameters: the file to be hashed and the file to write the hash to.
There is no need to create a concrete implementation, though, because Gradle will generate one for us at runtime.

.buildSrc/src/main/java/MD5WorkParameters.java
[source,java]
----
include::{snippetsPath}/workerApi/md5NoIsolation/groovy/buildSrc/src/main/java/MD5WorkParameters.java[]
----
<1> Use `Property` objects to represent the source and MD5 hash files.

Second, you'll need to refactor the part of your custom task that does the work for each individual file into a separate class.
This class is your "unit of work" implementation and it should be an abstract class that extends `org.gradle.workers.WorkAction`.

.buildSrc/src/main/java/GenerateMD5.java
[source,java]
----
include::{snippetsPath}/workerApi/md5NoIsolation/groovy/buildSrc/src/main/java/GenerateMD5.java[]
----
<1> Do not implement the `getParameters()` method - Gradle will inject this at runtime.

Now, you should change your custom task class to submit work to the
link:{javadocPath}/org/gradle/workers/WorkerExecutor.html[WorkerExecutor] instead of doing the work itself.

.buildSrc/src/main/java/CreateMD5.java
[source,java]
----
include::{snippetsPath}/workerApi/md5NoIsolation/groovy/buildSrc/src/main/java/CreateMD5.java[]
----
<1> You'll need to have the link:{javadocPath}/org/gradle/workers/WorkerExecutor.html[WorkerExecutor] service in order to submit your work.
    Create a abstract getter methods annotated `javax.inject.Inject` and Gradle will inject the service at runtime when the task is created.
<2> Before submitting work, you'll need to get a `WorkQueue` object with the desired isolation mode.
    We'll talk more about isolation modes later.
<3> When submitting the unit of work, specify the unit of work implementation, in this case `GenerateMD5` and configure its parameters.

At this point, you should be able to try your task again.

[listing]
----
$ gradle clean md5

include::{snippetsPath}/workerApi/md5NoIsolation/tests/md5Task.out[]
----

The results should look the same as before, although the MD5 hash files may be generated in a different order due to the fact that the units of work are executed in parallel.
One thing you should notice, however, is that the task runs much faster.
This is because the Worker API executes the MD5 calculation for each file in parallel rather than in sequence.

== Changing the isolation mode

The isolation mode controls how strongly Gradle will isolate items of work from each other as well as from the rest of the Gradle runtime.
There are three methods on `WorkerExecutor` that control this:
`noIsolation()`, `classLoaderIsolation()` and `processIsolation()`.
The `noIsolation()` mode is the lowest level of isolation and will prevent a unit of work from changing the project state.
This is the fastest isolation mode because it requires the least overhead to set up the work item to execute, so you'll probably want to use this for simple cases.
However, it will use a single shared classloader for all units of work.
This means that each unit of work can potentially affect one another through static class state.
It also means that every unit of work uses the same version of libraries that are on the buildscript classpath.
If you wanted the user to be able to configure the task to run with a different (but compatible) version of the
https://commons.apache.org/proper/commons-codec/[Apache Commons Codec] library, you would need to use a different isolation mode.

First, you'll want to change the dependency in `buildSrc/build.gradle` to be `compileOnly`.
This tells Gradle that it should use this dependency when building the classes, but should not put it on the build script classpath.

====
include::sample[dir="snippets/workerApi/md5ClassloaderIsolation/kotlin",files="buildSrc/build.gradle.kts[]"]
include::sample[dir="snippets/workerApi/md5ClassloaderIsolation/groovy",files="buildSrc/build.gradle[]"]
====

Next, you'll want to change the `CreateMD5` task to allow the user to configure the version of the codec library that they want to use.
It'll resolve the appropriate version of the library at runtime and configure the workers to use this version.
The `classLoaderIsolation()` method tells Gradle to run this work in a thread with an isolated classloader.

.buildSrc/src/main/java/CreateMD5.java
[source, groovy]
----
include::{snippetsPath}/workerApi/md5ClassloaderIsolation/groovy/buildSrc/src/main/java/CreateMD5.java[]
----
<1> Expose an input property for the codec library classpath.
<2> Configure the classpath on the link:{javadocPath}/org/gradle/workers/ClassLoaderWorkerSpec.html[ClassLoaderWorkerSpec] when creating the work queue.

Next, you'll need to configure your build so that it has a repository to look up the codec version at task execution time.
We'll also create a dependency to resolve our codec library from this repository.

====
include::sample[dir="snippets/workerApi/md5ClassloaderIsolation/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/workerApi/md5ClassloaderIsolation/groovy",files="build.gradle[]"]
====

<1> Add a repository to resolve the codec library - this can be a different repository than the one used to build the `CreateMD5` task class.
<2> Add a _configuration_ to resolve our codec library version.
<3> Configure an alternate, compatible version of https://commons.apache.org/proper/commons-codec/[Apache Commons Codec].
<4> Configure the `md5` task to use the configuration as its classpath.
    Note that the configuration will not be resolved until the task is actually executed.

Now, if you run your task, it should work as expected using the configured version of the codec library:

[listing]
----
$ gradle clean md5

include::{snippetsPath}/workerApi/md5ClassloaderIsolation/tests/md5Task.out[]
----

== Creating a Worker Daemon

Sometimes it is desirable to create even further isolation when executing items of work.
For instance, external libraries may rely on certain system properties to be set which may conflict between work items.
Or a library might not be compatible with the version of JDK that Gradle is running with and may need to be run with a different version.
The Worker API can accommodate this using the `processIsolation()` method that causes the work to execute in a separate "worker daemon".
These worker daemon processes will persist across builds and can be reused during subsequent builds.
If system resources get low, however, Gradle will stop any unused worker daemons.

To utilize a worker daemon, simply use the `processIsolation()` method when creating the `WorkQueue`.
You may also want to configure custom settings for the new process.

.buildSrc/src/main/java/CreateMD5.java
[source,java]
----
include::{snippetsPath}/workerApi/md5ProcessIsolation/groovy/buildSrc/src/main/java/CreateMD5.java[]
----
<1> Change the isolation mode to `PROCESS`.
<2> Set up the link:{javadocPath}/org/gradle/process/JavaForkOptions.html[JavaForkOptions] for the new process.

Now, you should be able to run your task, and it will work as expected but using worker daemons instead:

[listing]
----
$ gradle clean md5

include::{snippetsPath}/workerApi/md5ProcessIsolation/tests/md5Task.out[]
----

Note that the execution time may be somewhat high.
This is because Gradle has to start a new process for each worker daemon, which is expensive.
However, if you run your task again, you'll see that it runs much faster.
This is because the worker daemon(s) started during the initial build have persisted and are available for use immediately during subsequent builds.

[listing]
----
$ gradle clean md5

include::{snippetsPath}/workerApi/md5ProcessIsolation/tests/md5Task.out[]
----
