Closing a java.util.Iterator

前端 未结 7 1787
清酒与你
清酒与你 2020-12-29 02:32

I\'ve implemented a custom java.util.Iterator using a resource that should be released at the end using a close() method. That resource could

7条回答
  •  無奈伤痛
    2020-12-29 03:11

    You could close it in a finalizer but it's not going to give you the behavior you want. Your finalizer is called only when the garbage collector wants to cleanup your object, so your resource might remain open. Worse, if someone holds onto your iterator, it'll never close.

    There's a possibility of closing the stream on the first call to hasNext() that returns false. That's still not guaranteed to do it since someone might iterate only the first element and never bother with it again.

    Really, I think you'll need to manage it yourself when dealing with an external library. You're going to make those calls to the methods that use the iterable, so why not close it yourself when you're done? Resource management is not something you can just impose on an external library that doesn't know any better.

提交回复
热议问题