【问题标题】:What if new fails?如果 new 失败了怎么办?
【发布时间】:2011-06-14 16:40:57
【问题描述】:

在 C++ 和 C# 中,当 new 无法分配足够的内存时,它会引发异常。

我在 Java 中找不到任何关于 new 行为的信息。 那么如果 new 在 Java 中失败(内存不足)会发生什么?

【问题讨论】:

    标签: java memory-management


    【解决方案1】:

    假设你特别意味着内存分配失败,那么它应该抛出OutOfMemoryError

    当 Java 虚拟机因为内存不足而无法分配对象时抛出,并且垃圾收集器无法提供更多内存。

    像Error 的所有子类一样,它通常是不可恢复的状态,即使从技术上您可以捕获它:

    错误是 Throwable 的子类,表示合理的应用程序不应尝试捕获的严重问题。大多数此类错误是异常情况。 ThreadDeath 错误虽然是“正常”情况,但也是 Error 的子类,因为大多数应用程序不应尝试捕获它。

    方法不需要在其 throws 子句中声明任何可能在方法执行期间抛出但未被捕获的 Error 子类,因为这些错误是不应该发生的异常情况。

    【讨论】:

    • 可以编写从这种情况中恢复的代码,前提是您有充分的理由将其捕获到已知问题。这很少是一个好主意,减少消耗的内存或增加最大内存通常是最好的选择。
    【解决方案2】:

    当 Java 无法获得足够的内存来分配对象时,您将获得 OutOfMemoryError。

    实际上,JVM 实际抛出异常可能需要相当长的时间。当遇到内存问题时,JVM 会首先尝试尽可能多地回收内存。根据 JVM 配置(GC 参数和最大堆内存),GC 周期可能需要几秒钟到几分钟,而 Xmx 设置为几 GB。更糟糕的是,根据所需的内存,JVM 可以在抛出异常之前执行几个 GC 周期。

    当异常被抛出时,它被当作任何未捕获的异常处理。因此,它将传播到引发异常的线程的调用堆栈的顶部。由于未捕获异常,线程将在死前在System.err 上显示堆栈跟踪。就这样。在单线程程序中,这将导致程序退出。在多线程程序上,这种线程死亡可以释放足够的内存,让程序在不稳定的配置下继续运行。

    如果您担心内存问题,我的建议是您应该注册并UncaughtExceptionHandler 在出现内存问题时终止您的程序,因为停止您的程序肯定比让它在没有任何人的情况下工作在未定义状态更好知道。

    您可以阅读 Heinz Kabutz 关于该主题的以下文章:

    【讨论】:

      【解决方案3】:

      如果你真的没有足够的内存 OutOfMemoryError 被抛出。 构造函数本身也可能抛出任何异常。

      【讨论】:

        【解决方案4】:

        更多关于OOME。

        /*License - LGPL
        <h3>Recovery from an OutOfMemory Error</h3>
        <p>The JavaDocs for Error state, in the first sentence..
        
        <blockquote>"An Error is a subclass of Throwable that indicates
        serious problems that a reasonable application should
        not try to catch."</blockquote>
        
        <p>This advice has led to the fallacy that an OutOfMemoryError
        should not be caught and dealt with.  But this demo. shows
        that it is quite easy to recover to the point of providing
        the user with meaningful information, and advice on how to
        proceed.
        
        <p>I aim to make my applications 'unreasonable'.  ;-)
        */
        
        import java.awt.event.ActionListener;
        import java.awt.event.ActionEvent;
        import java.awt.event.WindowAdapter;
        import java.awt.event.WindowEvent;
        
        import javax.swing.JPanel;
        import javax.swing.JLabel;
        import javax.swing.JProgressBar;
        import javax.swing.JOptionPane;
        import javax.swing.JDialog;
        import javax.swing.Timer;
        
        import javax.swing.border.EmptyBorder;
        
        import java.util.ArrayList;
        
        /** A demo. showing recovery from an OutOfMemoryError.
        Our options once an OOME is encountered are relatively
        few, but we can still warn the end user and provide
        advice on how to correct the problem.
        @author Andrew Thompson */
        public class MemoryRecoveryTest {
        
            public static void main(String[] args) {
                // reserve a buffer of memory
                byte[] buffer = new byte[2^10];
                ArrayList<Object> list = new ArrayList<Object>();
                final JProgressBar memory = new JProgressBar(
                    0,
                    (int)Runtime.getRuntime().totalMemory());
                ActionListener listener = new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        memory.setValue(
                            (int)Runtime.getRuntime().freeMemory() );
                    }
                };
                Timer timer = new Timer(500, listener);
                timer.start();
        
                JDialog dialog = new JDialog();
                dialog.setTitle("Available Memory");
                JPanel memoryPanel = new JPanel();
                memoryPanel.add(memory);
                memoryPanel.setBorder(new EmptyBorder(25,25,25,25));
                dialog.add( memoryPanel );
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                dialog.addWindowListener( new WindowAdapter(){
                    @Override
                    public void windowClosing(WindowEvent we) {
                        System.exit(0);
                    }
                } );
        
                // prepare a memory warning panel in advance
                JPanel memoryWarning = new JPanel();
                memoryWarning.add( new JLabel(
                    "<HTML><BODY>There is not enough memory to" +
                    " complete the task!<BR> Use a variant " +
                    " of the application that assigns more memory.") );
        
                try {
                    // do our 'memory intensive' task
                    while(true) {
                        list.add( new Object() );
                    }
                } catch(OutOfMemoryError oome) {
                    // provide the VM with some memory 'breathing space'
                    // by clearing the buffer
                    buffer = null;
                    // tell the user what went wrong, and how to fix it
                    JOptionPane.showMessageDialog(
                        dialog,
                        memoryWarning,
                        "Out of Memory!",
                        JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        

        【讨论】:

        【解决方案5】:

        您可以捕获 OutOfMemoryExceptions 但不推荐。但是,除非是编码/设计问题 - 垃圾收集器应该负责管理堆。

        如果您认为您将进行大量数据处理并且可能会耗尽内存,那么您始终可以在开始执行之前检查可用空间(从link 复制代码 sn-p)。

        // 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();
        

        【讨论】:

        • OOM 不仅是由于编码/设计问题,至少不是您始终可以控制的问题。我想到了著名的 3rd 方 API 中的内存泄漏,这在 Java 的生命周期中非常普遍(而且肯定会继续存在)...
        • 在我看来,选择第三方 API 是设计的一部分。
        猜你喜欢
        • 2012-08-01
        • 1970-01-01
        • 2011-04-26
        • 1970-01-01
        • 2019-02-10
        • 2010-12-31
        • 2016-01-11
        • 2018-10-21
        • 1970-01-01
        相关资源
        最近更新 更多