javamemory-leaksautocloseable

Is allocating new instance of Closeable to previously created instance, closing previous?


For example Scanner class, which implements Closeable interface:

Scanner sc = new Scanner(...);
sc.//do smthing
sc = new Scanner(...); <- is previous Scanner closed? Does it create memory leak?
sc.//do smthing
sc.close();

Solution

  • No, unless you explicitly call sc.close(), or scope it in a try-with-resources block, there are no guarantees it will be closed. Some classes might have a finalizer or an associated Cleaner, but these are very unreliable (as in, you never know when or even if they will get called).