No-throw VirtualMachineError guarantees

喜你入骨 提交于 2019-11-26 13:47:25
Raedwald

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 one of several tasks fails because it needs too much memory we might want to continue with the other tasks.

kosa

If it is resource limitation, on the first place, no operations takes place. Here is link for perfect example to have VirtualMachineError. Virtual machine error

This error is not something like OutofMemoryError, where by that time some operations might be in progress.

I see that you've answered your own question and I can understand why this would be mildly surprising to you, coming from a strict C++ background. This is just the reality of managed memory (virtual) machines and it's not limited to just java. Memory can run out, as the JVM is bounded to how much heap it can use (configurable on the java command line).

Somewhat analogous, but not equivalent, in the C++/machine-code world would be a GENERAL_PROTECTION_FAULT (or SEGMENTATION_FAULT if you're on *NIX) that you would get when attempting to address memory that has not been allocated or is outside your virtual address space. Providing a "strong exception guarantee" in the face of that scenario is equally difficult as the cause may be either a bug in code or completely outside the control of the program.

Peter Lawrey

In Java, you can call Thread.stop() or stop(Throwable) at any time. Most errors are considered so critical that you should not try to handle them unless you really know what you are doing.

Having developed server side Java application for 12 years, I can say I have never heard of anyone worrying about random exceptions being thrown. I suspect its just not an issue you need to worry about with Java.

Can you give an example of why you believe you need a guarantee, as there is likely to be another way to solve the problem?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!