Is the garbage collector guaranteed to run before Out of Memory Error?

后端 未结 5 1211
清酒与你
清酒与你 2020-12-01 21:12

In case the heap is full, the JVM throws an OutOfMemoryError. But is it assured that a (full) garbage collection always takes place before such an exception is thrown?

5条回答
  •  悲&欢浪女
    2020-12-01 21:32

    You are not guaranteed that a full garbage collection has been performed, but that the VM has tried to make enough memory available through garbage collection. You could have found that in the API documentation for the OutOfMemoryError class:

    Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

    Note that there are cases where the garbage collector can decide that enough memory is not available without actually trying to discard unreferenced object instances. The most obvious example is if you try to allocate more memory in one go (e.g. a large byte array) than the max heap size. In this case, an OutOfMemoryError may be thrown without the garbage collector being run at all.

提交回复
热议问题