What if new fails?

前端 未结 5 2067
终归单人心
终归单人心 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:30

    You can catch for OutOfMemoryExceptions but not recommended. However, unless it's a coding/design issue - the garbage collector should take care of managing the heap.

    If you think you will be doing large amount of data processing and may run of memory then you can always check for the free space available before beginning execution (copied the code snippet from this link).

    // Get current size of heap in bytes
    long heapSize = Runtime.getRuntime().totalMemory();
    
    // Get maximum size of heap in bytes. The heap cannot grow beyond this size.
    // Any attempt will result in an OutOfMemoryException.
    long heapMaxSize = Runtime.getRuntime().maxMemory();
    
    // Get amount of free memory within the heap in bytes. This size will increase
    // after garbage collection and decrease as new objects are created.
    long heapFreeSize = Runtime.getRuntime().freeMemory();
    

提交回复
热议问题