1

This question is a duplicate of this question but none of them answered if it can be closed.

They only suggested alternatives- using try-with or actually having a reference like Scanner scanner=new Scanner(System.in).

This led to me thinking that unreferenced Scanner objects can't be closed but...

Question: Shouldn't the objects become eligible for garbage collection and thus will be closed ultimately?
(Note: I do realise that depending on the GC isn't a great idea)

HelloWorld
  • 193
  • 2
  • 8

1 Answers1

3

Looking at the OpenJDK source, Scanner doesn't override the finalize method. This means no special code is executed when the object is eventually collected, and you need to close it explicitly.

EDIT:
This is probably intentional, since a common usecase for Scanner is to use it on System.in, which you should never close.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    In short, the object is garbage collected, but the underlying stream is still open? – HelloWorld Dec 16 '20 at 00:15
  • @HelloWorld yes, exactly – Mureinik Dec 16 '20 at 04:06
  • 1
    In general, objects wrapping another resource object will never have a finalizer closing them, as it is always possible that a wrapper gets garbage collected while the underlying resource is still in use, like in [this Q&A](https://stackoverflow.com/q/26642153/2711488). So, the `Scanner` does not have a finalizer or cleaner, but the underlying resource, e.g. when wrapping a `FileInputStream`, may have. Still, this is not an invitation to rely on garbage collection of resources. The case of `System.in` [is special](https://stackoverflow.com/q/54822835/2711488)… – Holger Dec 16 '20 at 10:01