Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No-throw VirtualMachineError guarantees

I've come to Java from C++. In the C++ world we pay attention to exception safety, and note that mutators can provide different guarantees in the face of exceptions thrown by the mutator itself or a method it delegates to (minimum, strong, no-throw). Implementing a method that has a strong exception guarantee requires that some basic operations are guaranteed never to throw an exception. The JLS makes statements about which operations can throw which kinds of exceptions, but the VirtualMachineError error presents a problem. Quoth the JLS:

an internal error or resource limitation prevents the Java virtual machine from implementing the semantics of the Java programming language; in this case, an instance of a subclass of VirtualMachineError is thrown.

The JLS says no more about VirtualMachineError. An "internal error" means a bug in the JVM, so I'm not interested in that case: in the face of bugs in the JVM, all bets are off. But what about the "resource limitation" case? Are there any operations that are guaranteed never to fail because of a resource limitation?

like image 275
Raedwald Avatar asked Jan 04 '12 14:01

Raedwald


1 Answers

Quoth the Java Virtual Machine Specification:

This specification cannot predict where internal errors or resource limitations may be encountered and does not mandate precisely when they can be reported. Thus, any of the VirtualMachineError subclasses defined below may be thrown at any time during the operation of the Java virtual machine:

In Java therefore no exception guarantees can be made with respect to VirtualMachineError exceptions. All exception guarantees must be subject to the qualification "... but not if a VirtualMachineError is thrown". This is one of the ways in which Java is different from C++.

This also suggests that there is not much point in catching a VirtualMachineError exception, because the program is in an undefined state if one has been thrown. That unfortunately includes OutOfMemoryError exceptions. Unfortunate, because if a program has several independent tasks to perform (for example, a web server), if one task fails because it needs too much memory, we might want to continue with the other tasks.

like image 200
Raedwald Avatar answered Sep 22 '22 07:09

Raedwald