To run dex in process, the Gradle daemon needs a larger heap.
It currently has 1024 MB.
For faster builds, increase the maximum heap size for the Gradle daemon to at least 4608 MB (based on the dexOptions.javaMaxHeapSize = 4g).
To do this set org.gradle.jvmargs=-Xmx4608M in the project gradle.properties.
For more information see https://docs.gradle.org/current/userguide/build_environment.html