Java resource closing

后端 未结 8 1653
一生所求
一生所求 2021-01-12 00:57

I\'m writing an app that connect to a website and read one line from it. I do it like this:

try{
        URLConnection connection = new URL(\"www.example.com         


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 01:20

    The general idiom for resource acquisition and release in Java is:

    final Resource resource = acquire();
    try {
        use(resource);
    } finally {
        resource.release();
    }
    

    Note:

    • try should immediately follow the acquire. This means you can't wrap it in the decorator and maintain safety (and removing spaces or putting things on one line doesn't help:).
    • One release per finally, otherwise it wont be exception safe.
    • Avoid null, use final. Otherwise you'll have messy code and potential for NPEs.
    • Generally there is no need to close the decorator unless it has a further resource associated with it. However, you will generally need to flush outputs, but avoid that in the exception case.
    • The exception should either be passed through to the caller, or caught from a surrounding try block (Java leads you astray here).

    ou can abstract this nonsense with the Execute Around idiom, so you don't have to repeat yourself (just write a lot of boilerplate).

提交回复
热议问题