出现 OutOfMemoryError 后,Spring REST 服务不会关闭

ric*_*din 6 java spring spring-mvc out-of-memory spring-boot

我正在经历我认为的 Java 应用程序的奇怪行为。我正在使用 Spring Boot 1.4.1 来开发 REST 服务。由于我的代码中的错误,对服务的调用会导致OutOfMemoryError.

出人意料的是,该服务通过以下消息响应生成错误的请求:

{
  "timestamp": 1487862480405,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "java.lang.OutOfMemoryError",
  "message": "No message available",
  "path": "/entity/exportCsv"
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。更令人惊讶的是,REST 服务在遇到Error. 有人说,Error最好的办法是正确记录并关闭所有内容。错误的存在应该意味着系统处于不可恢复的状态。

为什么 Spring MVC 会采用如此奇怪的策略Error?发生事件后是否可以强制退出应用程序(REST 服务)Error

如果要重现上述用例,只需使用以下代码。

@RestController
@RequestMapping("/entity")
class Controller {
    @RequestMapping(value = "/exportCsv", method = RequestMethod.GET)
    ResponseEntity exportCsv() {
        if (true)
            throw new OutOfMemoryError();
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢大家。

编辑:如果您确实认为捕获 anError是开发 Java 应用程序的正常方式,请尝试查看这些参考资料:

Ser*_*ema 5

运行应用程序时,您可以使用以下参数指定发生此类错误时应用程序的行为:

  • -XX:+HeapDumpOnOutOfMemoryError:这将创建一个转储,可以在之后进行分析。转储将位于 给出的位置-XX:HeapDumpPath=some_path
  • -XX:OnOutOfMemoryError=path_to_some_script.sh :当应用程序将错误作为 OutOfMemory 返回时,这将运行一个脚本(它必须由运行该应用程序的同一用户运行)
  • -XX:OnError=path_to_some_script.sh : 和以前一样,但对于更通用的例外。

参考:http : //www.oracle.com/technetwork/java/javase/clopts-139448.html