85

How do I fix java.lang.OutOfMemoryError: Java heap space when compiling my Android project?

I get this after I upgraded to version 1 of Android Studio. But, I don't think this is the problem. Most likely when I start upgrading my app to SDK 21 (before this was SDK 20). But I wasn't so sure either.

I've googled around for some fix, but couldn't find one that works. Most of the fix are for Eclipse IDE.

This is the full logcat error that I get when compiling:

warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.

UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: Java heap space
    at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
    at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
    at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
    at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
    at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
    at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
    at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
    at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
    at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
    at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
    at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
    at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
    at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
    at com.android.dx.command.dexer.Main.processClass(Main.java:729)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
    at com.android.dx.command.dexer.Main.access$300(Main.java:82)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:632)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
    at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
    at com.android.dx.command.dexer.Main.run(Main.java:243)
    at com.android.dx.command.dexer.Main.main(Main.java:214)
    at com.android.dx.command.Main.main(Main.java:106)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\sdfasd\android-sdks\build-tools\21.1.1\dx.bat --dex --no-optimize --multi-dex --main-dex-list C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\multi-dex\debug\maindexlist.txt --output C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\dex\debug --input-list=C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
    3
Output:
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    
    UNEXPECTED TOP-LEVEL ERROR:
    java.lang.OutOfMemoryError: Java heap space
        at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
        at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
        at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
        at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
        at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
        at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
        at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
        at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
        at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
        at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
        at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
        at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
        at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
        at com.android.dx.command.dexer.Main.processClass(Main.java:729)
        at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
        at com.android.dx.command.dexer.Main.access$300(Main.java:82)
        at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
        at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
        at com.android.dx.command.dexer.Main.processOne(Main.java:632)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
        at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
        at com.android.dx.command.dexer.Main.run(Main.java:243)
        at com.android.dx.command.dexer.Main.main(Main.java:214)
        at com.android.dx.command.Main.main(Main.java:106)

Is it because of one jar library I used (zip4j)? I did try to remove it, but the OOM error still occurs. Any idea how to fix this?


Edit:

I've also edited gradlew file to increase the -Xmx size.

GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\" \"-Xmx2048M \"-XX:MaxPermSize=512M\" \"-XX:ReservedCodeCacheSize=512M\""

Nothing changes.


Edit 2:

Also did this fix but couldn't help it too:

Try the following:

Ctrl + Alt + S -> Compiler -> Gradle

InVM Options field write:

-Xmx2048m -XX:MaxPermSize=512m
emen
  • 6,050
  • 11
  • 57
  • 94
  • Check heap dump ...you also can add android:largeHeap="true" – Prachi Dec 12 '14 at 06:44
  • @Prachi nothing helps. I can't even compile and run it, how am I suppose to check the heap dump? – emen Dec 12 '14 at 07:14
  • Edited. Added a fix I did in gradlew file. – emen Dec 12 '14 at 07:33
  • I have tried this [Solution](https://stackoverflow.com/a/55429299/10288513) and it worked for me. – Gourav Samre Mar 30 '19 at 07:49
  • If anyone comes across this problem and is on AS 3.5+ on Mac, you can try [this GitHub](https://github.com/gradle/gradle/issues/8139#issuecomment-543050424) solution. Among the ocean of different answers here on SO, this was what worked for me (and many others by comment's the reactions). – Ícaro Feb 19 '20 at 21:41

19 Answers19

82

Update 2022; DSL element 'dexOptions' is obsolete and should be removed. It will be removed in version 8.0 of the Android Gradle plugin.
Using it has no effect, and the AndroidGradle plugin optimizes dexing automatically.

I tested and with Gradle 7.0+, increasing below mentioned org.gradle.jvmargs option is all we need.

Original Answer

I had a similar issue on Android Studio 2.3.3. APK packaging would fail saying Java heap space when building from Android Studio and trying to process a 300MB .so library. In my case two things were needed to fix it. Your build.gradle should contain something like that:

android {
    dexOptions {
        javaMaxHeapSize "4G"
    }
}

At the root of your project you need to have a file named gradle.properties containing the following:

# That's needed for java to be able the create the APK with our 300MB native  library
# Basically we grant java a 4GB heap.
org.gradle.jvmargs=-Xmx4608m
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Slion
  • 2,558
  • 2
  • 23
  • 27
34

This is old, but just add this to the build file

dexOptions {
    javaMaxHeapSize "2g"
}
Graeme
  • 1,107
  • 2
  • 12
  • 30
20

Build => Clean Project

then

Build => Rebuild Project

When I do this, it always fixes for me.

Ferit Kartal
  • 201
  • 2
  • 3
  • 3
    I see this advice in a lot of issues and it's true that a rebuild can fix most of them. What bothers me is why we have to clean first? Isn't rebuild automatically do a clean? – rtsketo Nov 26 '20 at 12:53
  • Actually `Rebuild Project` contains `Clean Project`. So it doesn't need to `Clean Project`, if you are going to `Rebuild Project`. – Isaac Lee Apr 18 '22 at 13:18
12

You can do this with the UI in Android Studio, with friendly defaults

Click File > Settings from the menu bar (or Android Studio > Preferences on macOS).
Click Appearance & Behavior > System Settings > Memory Settings.

Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135
  • 2
    To put it more nicely than the previous comments did: This answer would be *better* if it also described in text, in the answer, exactly what to do. Linked pages can change, as this one has: it no longer jumps to the highlighted text you included in the link. All a screen reader user can see here is "enter image description here". – Ryan M Apr 27 '22 at 21:32
  • note, global settings will be overriden by properties.gradle, and just commenting the line will not help. I had have to set Xmx2048 despite on global memory setting 4096 – djdance Apr 17 '23 at 07:18
11

Open gradle.properties files in the root of you project

Add this line:

# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

Just remove # in front of the line.

emen
  • 6,050
  • 11
  • 57
  • 94
ItSNeverLate
  • 533
  • 7
  • 8
10

I've finally solved it by limiting the Google Play service in gradle dependency.

The problem however was caused by the Google Play service, and by simply change it to a specific library, it is now solved.

 com.google.android.gms:play-services-base:6.5.87

UPDATE

More info on android guides

emen
  • 6,050
  • 11
  • 57
  • 94
8

assign more memory to Gradle in the project's gradle.properties file.For example:

org.gradle.jvmargs=-Xmx1024m

HongGang Jing
  • 81
  • 1
  • 3
6

Change the following line in properties.gradle to a higher number as shown below

org.gradle.jvmargs=-Xmx1132m

to

org.gradle.jvmargs=-Xmx2048m
emen
  • 6,050
  • 11
  • 57
  • 94
sadiq rashid
  • 468
  • 5
  • 8
5

Here is what I did:

1st step: In your App, go to GRADLE SCRIPTS -> GRADLE.PROPERTIES -> change org.gradle.jvmargs=-Xmxm to org.gradle.jvmargs=-Xmx4G

2nd Step: In your App, go to GRADLE SCRIPTS -> build.gradle -> in the android{

//add this line:

dexOptions {
   javaMaxHeapSize = "4G"
   }
}
4

i'm using Windows OS. I solved this by updating _JAVA_OPTIONS to '-Xmx1024m'

  1. Win + X, choose SYSTEM
  2. Choose 'Advanced system settings'
  3. Choose 'Environment Variables'
  4. Create / Edit a variable named as '_JAVA_OPTIONS'
  5. update variable value as -Xmx1024m

click to see snapshot

3

You have changed the wrong arguments, you should increase the size on -XX:MaxPermSize=512M to -XX:MaxPermSize=2048M or so :) because the android emulator uses a lot of RAM.

emen
  • 6,050
  • 11
  • 57
  • 94
aurelius
  • 3,946
  • 7
  • 40
  • 73
  • Same error :( Should I add more memory to the maxperm? – emen Dec 12 '14 at 08:01
  • yes, do that and see what happens :) BTW: how much RAM do you have on your machine? – aurelius Dec 12 '14 at 08:35
  • This is not correct, XX:MaxPermSize is used to store "data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level. For example objects describing classes and methods are stored in the permanent generation." (http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html) I can hardly think of any scenario where AimanB's code and Android Studio would require more than 512MB of RAM to store Classes (*not* Objects) and Methods. The problem lie elsewhere – Kai Dec 12 '14 at 08:36
  • 1
    You have a point there. Maybe the best thing now would be to create a dump with jvisualVM (it's in the bin folder of your jdk) and then analyze it with MAT, which is free and better for analyzing dumps. – aurelius Dec 12 '14 at 08:41
  • start the jvisualVM before you start the emulator, and you can see in the left side of jvisualVM's window the active processes, start then the emulator, you will see in JVM the emulator's process and open the monitor tab, you will see how much heap will allocate for the process. After your java android process crashes create a dump with JVM and then open that dump with MAT and investigate all the leaks. – aurelius Dec 12 '14 at 08:44
3

The answers above are for gradle builds (or the general -Xmx). In case someone gets here for a non-gradle project, I solved the issue by increasing the maximum heap size of DEX in android studio settings => Build, Execution, Deployment => Compiler => Android Compilers

chef
  • 531
  • 4
  • 9
  • I found this config in File - > other Settings -> Default Settings -> Build, Execution, Deployment -> Compiler -> Android Compilers – mianlaoshu Mar 01 '17 at 09:57
2

I have faced to the same problem after lots of research I found this solution. you can solve this problem by changing this. go to gradle.properties and change

org.gradle.jvmargs=-Xmx500m

to

org.gradle.jvmargs=-Xmx2048m
emen
  • 6,050
  • 11
  • 57
  • 94
1

None of the answers worked for me but finally I found something that worked in my case:

Automatically managing paging files size

In windows:

  1. Under "Advanced System Settings"
  2. Advanced Tab
  3. Performance section, settings...
  4. Advanced Tab
  5. Virtual memory... Change...
  6. Select Automatically manage paging files size for all drives

I don't remember why I had this unchecked but this was causing trouble in my gradle builds (with flutter).

Jorge
  • 1,350
  • 2
  • 10
  • 19
1

Close emulator and then build. Default doesn't allow both at once for me

Dazzle
  • 2,880
  • 3
  • 25
  • 52
1

Just add this in your gradle.properties file, to avoid this bug.

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-XX:+UseParallelGC -Xmx2048M -Dkotlin.daemon.jvm.options\="-Xmx4608m" -XX\:MaxPermSize\=1024m -XX\:+HeapDumpOnOutOfMemoryError -Dfile.encoding\=UTF-8
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
#avoid check for debug
gradle=build -x lint -x lintVitalRelease
#decreases the startup & execution time
org.gradle.deamon=true
#build project in parallel (milti-module)
org.gradle.parallel=true
#store task outputs from previous builds
org.gradle.caching=true
#only required projects changes
org.gradle.configureondemand=true

But carefully study each line.

nicolas asinovich
  • 3,201
  • 3
  • 27
  • 37
1

The OOM happened to me after I edit a few lines of code in my project. The android studio freeze with some indexing... message.

I tried to force kill the app & restart as usually but not affect.

So I set:

  • in gradle.properties -> org.gradle.jvmargs=-Xmx8g -XX:MaxPermSize=4g
  • in /Users/user/Library/Application Support/Google/AndroidStudio4.2/studio.vmoptions -> -Xmx8g

and still nothing.

The UI was totally freeze & I couldn't do File -> Invalidate Cache/Restart Also, I tried to delete .gradle/caches but no affect.

To my luck, I had 2 versions of Android Studio: Arctic Fox & 4.2.

Android Studio 4.2 is the one that was totally freeze.

My hint was to:

  • open & rebuild the project with Android Studio Arctic Fix
  • open the project with Android Studio 4.2

I know there are hundreds of different suggested options, but nothing was helpful to me. So, decided to share my hint.

Hope, this will be useful.

obolsh
  • 129
  • 1
  • 4
0

This issue also may happen with usage of the debug build of Proguard. To solve it change minifyEnabled and shrinkResources to false.

android {
...
buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt')
    }

    debug {
        minifyEnabled false
        shrinkResources false
        proguardFiles getDefaultProguardFile('proguard-android.txt')
    }
} }  
twenk11k
  • 557
  • 5
  • 17
-2

Just add this to the gradle file:

android{
testOptions {
        ....
        unitTests.all {
            jvmArgs "-Xmx2g" // to avoid outOfMemory exception
        }
        ....
    }
}
Houssin Boulla
  • 2,687
  • 1
  • 16
  • 22