What if new fails?

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

    A little more on OOME.

    /*License - LGPL
    

    Recovery from an OutOfMemory Error

    The JavaDocs for Error state, in the first sentence..

    "An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch."

    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.

    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 list = new ArrayList(); 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( "There is not enough memory to" + " complete the task!
    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); } } }

    提交回复
    热议问题