0
byte[] largeByteArray = new byte[1000000000]; //1GB byte array
largeByteArray = null;

Will setting largeByteArray to null free the 1GB memory immediately or do we have to wait for garbage collector to release the 1GB?

If the answer is "we have to wait for GC" then is there any benefit of setting largeByteArray to null? Does it help the JVM somehow?

user794783
  • 3,619
  • 7
  • 36
  • 58
  • 1
    Same question for Android: [*Java: Setting Array to null to free memory*](https://stackoverflow.com/q/37705717/642706) – Basil Bourque Nov 19 '20 at 05:35
  • 1
    Dear Down-Voter, please leave a criticism along with your vote. This Question is valid and well-said (clear), albeit likely a duplicate. – Basil Bourque Nov 19 '20 at 05:37
  • 1
    Based on some quick research, the garbage seems to be lazy, as in it will only collect once it needs the space. So in practice it won't really have that much of an affect, and the code will run fine. That being said, if you were doing some kind of memory manipulation it might be important to know when exactly the gc (garbage collector) is run. You can manually call the GC with `System.gc()`, however this isn't recommended as it is sometimes ignored – Recessive Nov 19 '20 at 05:38
  • 1
    See also: [*Free memory of a byte array in Java*](https://stackoverflow.com/q/2974251/642706) – Basil Bourque Nov 19 '20 at 05:38
  • 1
    @Recessive (a) Various Java implementations come with various implementations of garbage collectors which vary in their behaviors, varying both by design and sometimes by runtime situations. Your first wo sentences are not of much use without referring to a specific garbage collector. (b) There is no recommendation I've seen *against* calling `System.gc()`. We must simply understand that doing so is a *request* to the garbage collector, not an order. The garbage collector may or may not abide, and if abiding, may do so now or may do so later. – Basil Bourque Nov 19 '20 at 05:42
  • 1
    @hajime As long as your `largeByteArray` variable holds a reference to the array, the array cannot be garbage-collected. You can clear that reference in any of three ways: (1) let the var go out of scope, (2) set the var to `null`, or (3) end your app’s execution. In the first two cases, if the array has no more references pointing to it, the array becomes a candidate for eventual garbage collection. The array may float around in memory for a while, but that is of no concern to you as the programmer or as the administrator. The key is to understand that your var is *not* the array. – Basil Bourque Nov 19 '20 at 05:45
  • 2
    @BasilBourque recommended read: [Can java finalize an object when it is still in scope?](https://stackoverflow.com/q/24376768/2711488) – Holger Nov 19 '20 at 07:50

0 Answers0