-3

In some case, I need to operator Doc file in Java, I usually need new a File instance, like:

File file = new File("path/to/target/file");

should I do somethine after I use it for release memory?

file = null;

seems not work well.

Zij.Fang
  • 21
  • 7
  • [java.io.File](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/io/File.html) don't need any housekeeping. What do you mean by "not work well"? GC don't immediately release the memory unless there's memory pressure or scheduled time is reached – Martheen Oct 16 '20 at 03:29
  • It's hard to know what Java is doing because it cleans up memory somewhat lazily via its garbage collectors. Why do you care about memory at a level like this? I've been programming in Java since it first came along, and I've never worried about things like this. Java will just take care of this stuff for you. – CryptoFool Oct 16 '20 at 03:30
  • 1
    The short answer is that you do not need to release memory. Java is a garbage collected language and it takes care of the memory management for you. (The exceptions are for instances of classes that hold non-heap resources such as open file descriptors, native memory segments and so on. These require special handling. But `File` is not of those classes!) – Stephen C Oct 16 '20 at 03:46
  • Specifically `file = null` simply breaks a link to a heap object. This has no immediate effect, and is probably a waste of time. If you have loaded a large "doc" file into memory, then the in-memory representation of the document won't be reachable via the `File` object anyway. It will be an instance of some other type. The `File` just encapsulates the file's pathname. Nothing else. – Stephen C Oct 16 '20 at 03:48

2 Answers2

1

file = null; [probably] won't do anything as long as the stream or reader you used to open the file still exists because that stream or reader [probably] will hold a reference to that File. And anyway, a File is virtually nothing in the bigger picture of memory consumption; it's highly unlikely your program will live or die over the continued existence of a single File object.

That said, there's certainly no harm in doing file = null; when you have no further use for that File instance. Just don't be either surprised or worried if the available memory doesn't instantly jump up by a few bytes!

Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21
1

First, a File instance is not much more than the file name. Its memory footprint is negligible.

Java has a garbage collector that will take care of reclaiming unused (unreachable) objects. There is no special action necessary on your side.

Henry
  • 42,982
  • 7
  • 68
  • 84