Gradle Android Invalid maximum heap size: Xmx4g

Get this error when execute the build task of an Android project with Gradle.

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Total time: 12.459 secs
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Invalid maximum heap size: -Xmx4g
The specified size exceeds the maximum representable size.
[sts] Build failed

This problem is connected with the Android dex, there are options in Gradle

    dexOptions {
        incremental true
        javaMaxHeapSize "4g"

The Dex is Dalvik VM executes. A dex file is similar to Jar file which contains byte code files, but it is run on Dalvik VM, not the JVM. Every Android application has its own Dalvik VM. Each VM is a standalone process managed by Linux.

The dex format is compact and is optimized for running on devices with limited memory, processor and other resources like mobile devices. Android provides tools that can convert Java class to dex format, usually this will shrink the size of the file about 50%.

Android first be compiled by Java Compiler then be converted to Dex file format.

In this example the javaMaxHeapSize specifies the -Xmx value when calling dx. Example value is "2048m". The dx is a tool shipped with Android SDK, in the build process, this tool will be called and perform the conversion from class file to dex file. The tool itself is a Jar file, Gradle need to launch a JVM to execute the tool, the javaMaxHeapSize should be parameter that passed to JVM.

You can set it to a lower value or just comment it out and use the default configuration.