Too many open file handles

前端 未结 12 1475
误落风尘
误落风尘 2020-12-16 03:00

I\'m working on a huge legacy Java application, with a lot of handwritten stuff, which nowadays you\'d let a framework handle.

The problem I\'m facing right now is

12条回答
  •  粉色の甜心
    2020-12-16 03:43

    This is a coding pattern that helps find unclosed resources. It closes the resources and also complains in the log about the problem.

    class
    {
        boolean closed = false;
        File file;
    
        close() {
            closed = true;
            file.close();
        }
    
        finalize() {
            if (!closed) {
                log error "OI! YOU FORGOT TO CLOSE A FILE!"
            file.close();
        }
    }
    

    Wrap the above file.close() calls in try-catch blocks that ignore errors.

    Also, Java 7 has a new 'try-with-resource' feature that can auto-close resources.

提交回复
热议问题