Execute plugin tasks with a Java Toolchain

Gradle version: 7.6.4

Hi

I need to convert an existing plugin to work with Java Toolchains.

I tried converting an existing custom task to use the Worker API and using processIsolation on the WorkerExecutor such that I can provide the toolchain executable.

I thought this would work, but the task I converted needs access to the Project. I tried to supply this as a Property, but DefaultProject is not serializable.

Can you recommend an alternative approach for executing a task using Java Toolchains when that task requires access to the Project?

Thanks in advance

Simon

You don’t necessarily need to use the Worker API for this, unless you have multiple things to do and want to make Gradle able to run them in parallel.

If all you want is to use the toolchain launcher, you can simple inject an instance of ExecOperations and then use something like

execOperations.javaexec {
    executable = launcher.get().executablePath.asFile.absolutePath
    ...
}

in your task action.

Besides that, if your task action needs the Project instance, this is bad practice anyway. With enabled STABLE_CONFIGURATION_CACHE feature preview also in Gradle 7 it is also deprecated to use the Project at execution time and latest if you try to use the configuration cache it is forbidden to use the Project at execution time.
So you should anyway refactor your task to remove that need.

See here for more information and strategies to avoid using Project at execution time: Configuration cache - Using the Project object

1 Like

Thanks very much for the fast and detailed response. @Vampire , just to be clear, we should not use the Project, for example, on any method annotated with @TaskAction on a Task?

Exactly.
Just enable the STABLE_CONFIGURATION_CACHE feature preview and you will get a deprecation warning if you do.
Or try to use the configuration cache (even though it is not officially stable in 7.6.4 yet) and it will fail.

Regarding the above. Is it possible to execute a TaskAction on a Task using Exec operations? i.e something without a main method

I’m not sure what you mean.
If you mean you want to execute one task from another task, this never was supported.
In oooold Gradle version there was an execute method on Task but this was never intended to be public API and is long gone and should never have been used due to many reasons.

Sorry if I was unclear. Let me try again.

I am currently using the Worker API to execute a WorkAction (this allows me to use toolchains)

Can I execute the same WorkAction using ExecOperations ?

Probably not, no.
I meant to understand that you already just called some external tool and changed it to worker API to be able to use toolchain.

If you have some code directly in that task class that you want to execute using toolchain, worker API is probably indeed the way to go.

1 Like