What if new fails?

前端 未结 5 2088
终归单人心
终归单人心 2021-01-02 02:05

In C++ and C# when new not able to allocate enought memory it throws exception.

I couldn\'t find any information about new\'s behavior in Java. So what will happen

5条回答
  •  清歌不尽
    2021-01-02 02:20

    When Java cannot get enough memory to allocate an object you'll get an OutOfMemoryError.

    In practice the exception can take quite a while to be actually thrown by the JVM. When faced to memory issue, the JVM will first try to garbage as much memory as possible. Depending on the JVM configuration (GC parameters and max heap memory), a GC cycle can take several seconds to several minutes with Xmx set to several gigabytes. Even worse, depending on the memory needed, the JVM can perform several GC cycles before throwing the exception.

    When the exception is throw, it is processed as any uncaught exception. As such it will propagate to the top of the calling stack of the thread where the exception was raised. As the exception is uncaught, the thread will display a stacktrace on System.err before dying. That's all. In a mono-threaded program this'll cause the program to exit. On a multi-threaded program, this thread death can free enough memory for the program to keep on running in an unstable configuration.

    My recommendation if you're concerned about memory issue is that you should register and UncaughtExceptionHandler to kill your program when a memory issue arises as it is certainly better to stop your program than letting it working in an undefined state without anyone knowing.

    You can read the following articles from Heinz Kabutz on the subject:

    • Catching Uncaught Exceptions in JDK 1.5
    • OutOfMemoryError Warning System

提交回复
热议问题