首页 > 解决方案 > Objects not freed after web-request

问题描述

I have encountered some weird problem/behavior Spring ResetController requests if I can call them like that. As I am not that familiar with Spring, maybe it is normal, I am just surprised, that after receiving some POST requests, objects I have created during a call is not being removed from memory.

@RequestMapping(method = RequestMethod.POST, value = "/run2")
public String api2() {

    try {
        new ServerSocket(8887);
        return "run2";
    } catch(Exception ex) {
        return "run2nok";
    }
}

With my understanding, each time I would call new ServerSocket(8887) I would be able to bind to a port, only if it's not being used. And as far as I can tell by this shortcode, its life-cycle should end after a return.

But when I make second POST call, its cant bind to a port, and by checking in CMD netstat | findstr: 8887 it is being used. But if I call System.gc() then the port is being freed, and I can make 2nd POST, like I need to.

So, does its normal, that object is still in use after the request has ended, or do I need to do something to free port?

标签: javaspring

解决方案


您永远不应该依赖于及时自动清理的东西——它可能立即发生、稍后发生或永远不会发生(甚至不能保证在响应时发生System.gc())。

如果您需要清理,请明确执行(例如,通过 finally,或使用 try-with-resources)。


推荐阅读