我在一个程序中得到这个错误,该程序创建了几个(数十万)HashMap对象,每个对象有几个(15-20)文本条目。在将这些字符串提交到数据库之前,必须收集所有这些字符串(而不将其分解为更小的数量)。

根据Sun的说法,错误发生在“如果在垃圾收集上花费了太多的时间:如果超过98%的总时间花在垃圾收集上,而不到2%的堆被恢复,则会抛出OutOfMemoryError”。

显然,可以使用命令行将参数传递给JVM

增加堆的大小,通过“-Xmx1024m”(或更多),或者 通过"-XX:-UseGCOverheadLimit"完全禁用错误检查。

第一种方法工作得很好,第二种方法在另一个java.lang中结束。OutOfMemoryError,这次是关于堆的。

那么,问题是:对于特定的用例(即几个小HashMap对象),是否有任何编程替代方案?例如,如果我使用HashMap clear()方法,问题就会消失,但存储在HashMap中的数据也会消失!: -)

该问题也在StackOverflow的相关主题中进行了讨论。


当前回答

The parallel collector will throw an OutOfMemoryError if too much time is being spent in garbage collection. In particular, if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

其他回答

您实际上正在耗尽内存,无法顺利运行进程。想到的选项有:

像你提到的那样指定更多的内存,首先尝试介于两者之间的内存,比如-Xmx512m 如果可能,使用更小批量的HashMap对象一次性处理 如果你有很多重复的字符串,在将它们放入HashMap之前,对它们使用String.intern() 使用HashMap(int initialCapacity, float loadFactor)构造函数针对您的情况进行调优

郑重声明,我们今天也遇到了同样的问题。我们通过使用这个选项来修复它:

-XX:-UseConcMarkSweepGC

显然,这修改了用于垃圾收集的策略,使问题消失了。

下面的方法对我很有效。只需添加以下片段:

dexOptions {
        javaMaxHeapSize "4g"
}

到你的建筑。gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'

    defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

这帮助我摆脱了这个错误。此选项将禁用 - xx: + DisableExplicitGC

使用替代HashMap实现(Trove)。标准Java HashMap有12倍的内存开销。 你可以在这里阅读细节。