How to delete an array properly in Java [duplicate]Deleting an object in java?List of objects that are still referenced after gc()Is Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?PHP: Delete an element from an arrayHow do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How do I remove a particular element from an array in JavaScript?How to use foreach with array in JavaScript?Why is it faster to process a sorted array than an unsorted array?

Are white and non-white police officers equally likely to kill black suspects?

New order #4: World

How to make payment on the internet without leaving a money trail?

If a centaur druid Wild Shapes into a Giant Elk, do their Charge features stack?

LWC and complex parameters

Is there a way to make member function NOT callable from constructor?

Does it makes sense to buy a new cycle to learn riding?

Where else does the Shulchan Aruch quote an authority by name?

How to answer pointed "are you quitting" questioning when I don't want them to suspect

Could Giant Ground Sloths have been a good pack animal for the ancient Mayans?

What do you call words made from common English words?

Does bootstrapped regression allow for inference?

Finding files for which a command fails

Copycat chess is back

Can a planet have a different gravitational pull depending on its location in orbit around its sun?

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?

How can I add custom success page

Pristine Bit Checking

Why is the design of haulage companies so “special”?

Prime joint compound before latex paint?

Manga about a female worker who got dragged into another world together with this high school girl and she was just told she's not needed anymore

How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)

What does 'script /dev/null' do?



How to delete an array properly in Java [duplicate]


Deleting an object in java?List of objects that are still referenced after gc()Is Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?PHP: Delete an element from an arrayHow do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How do I remove a particular element from an array in JavaScript?How to use foreach with array in JavaScript?Why is it faster to process a sorted array than an unsorted array?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11
















This question already has an answer here:



  • Deleting an object in java?

    7 answers



I'm 4 days old in Java and from the tutorials I've searched, the instructors focus a lot of effort in explaining how to allocate a two dimensional array (e.g.) as such:



Foo[][] fooArray = new Foo[2][3];


... but I've not found any that explains how to delete them.



From what is going on memory-wise, the variable fooArray will point to a block of memory in the heap, in which there are 2 elements. Each of the elements points to another block in the heap as well, which have 3 elements.



That being said, could I just reference the first block of elements and the garbage collector will do the job?



Foo[1] = null; and Foo[2] = null;



Or do I have to null each of the instantiated Foo elements?



Foo[1][1] = null; Foo[1][2] = null; Foo[1][3] = null; ...










share|improve this question















marked as duplicate by TT., Caleth, Mormegil, Iłya Bursov, Andrey Tyukin 9 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    @TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

    – Chronus
    17 hours ago







  • 4





    Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

    – TT.
    17 hours ago


















11
















This question already has an answer here:



  • Deleting an object in java?

    7 answers



I'm 4 days old in Java and from the tutorials I've searched, the instructors focus a lot of effort in explaining how to allocate a two dimensional array (e.g.) as such:



Foo[][] fooArray = new Foo[2][3];


... but I've not found any that explains how to delete them.



From what is going on memory-wise, the variable fooArray will point to a block of memory in the heap, in which there are 2 elements. Each of the elements points to another block in the heap as well, which have 3 elements.



That being said, could I just reference the first block of elements and the garbage collector will do the job?



Foo[1] = null; and Foo[2] = null;



Or do I have to null each of the instantiated Foo elements?



Foo[1][1] = null; Foo[1][2] = null; Foo[1][3] = null; ...










share|improve this question















marked as duplicate by TT., Caleth, Mormegil, Iłya Bursov, Andrey Tyukin 9 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    @TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

    – Chronus
    17 hours ago







  • 4





    Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

    – TT.
    17 hours ago














11












11








11


2







This question already has an answer here:



  • Deleting an object in java?

    7 answers



I'm 4 days old in Java and from the tutorials I've searched, the instructors focus a lot of effort in explaining how to allocate a two dimensional array (e.g.) as such:



Foo[][] fooArray = new Foo[2][3];


... but I've not found any that explains how to delete them.



From what is going on memory-wise, the variable fooArray will point to a block of memory in the heap, in which there are 2 elements. Each of the elements points to another block in the heap as well, which have 3 elements.



That being said, could I just reference the first block of elements and the garbage collector will do the job?



Foo[1] = null; and Foo[2] = null;



Or do I have to null each of the instantiated Foo elements?



Foo[1][1] = null; Foo[1][2] = null; Foo[1][3] = null; ...










share|improve this question

















This question already has an answer here:



  • Deleting an object in java?

    7 answers



I'm 4 days old in Java and from the tutorials I've searched, the instructors focus a lot of effort in explaining how to allocate a two dimensional array (e.g.) as such:



Foo[][] fooArray = new Foo[2][3];


... but I've not found any that explains how to delete them.



From what is going on memory-wise, the variable fooArray will point to a block of memory in the heap, in which there are 2 elements. Each of the elements points to another block in the heap as well, which have 3 elements.



That being said, could I just reference the first block of elements and the garbage collector will do the job?



Foo[1] = null; and Foo[2] = null;



Or do I have to null each of the instantiated Foo elements?



Foo[1][1] = null; Foo[1][2] = null; Foo[1][3] = null; ...





This question already has an answer here:



  • Deleting an object in java?

    7 answers







java arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 18 hours ago









Jason

9,62733545




9,62733545










asked 18 hours ago









ChronusChronus

1097




1097




marked as duplicate by TT., Caleth, Mormegil, Iłya Bursov, Andrey Tyukin 9 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by TT., Caleth, Mormegil, Iłya Bursov, Andrey Tyukin 9 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 1





    @TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

    – Chronus
    17 hours ago







  • 4





    Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

    – TT.
    17 hours ago













  • 1





    @TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

    – Chronus
    17 hours ago







  • 4





    Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

    – TT.
    17 hours ago








1




1





@TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

– Chronus
17 hours ago






@TT. although the answer is the same, my question was specific in arrays. Meaning that, even if I've read it before I asking, I would still be in doubt (from a nooby perspective)

– Chronus
17 hours ago





4




4





Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

– TT.
17 hours ago






Ok I hear you. Know that everything apart from primitive data types (e.g. int, double, ...) are objects. Important to know.

– TT.
17 hours ago













3 Answers
3






active

oldest

votes


















15














Explantion



You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either



  1. let the variable fall out of scope or

  2. assign null

  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.




References



To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector will delete anything which is not referenced. So let's take a look at an array such as:



int[][] outer = 1, 2, 3, 4, 5, 6;


We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:



 ___> 1, 2
|
outer --> int[][] ---|---> 3, 4
|
|___> 5, 6


So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.



Now assume that you would reference one of the inner arrays by another variable:



int[][] outer = 1, 2, 3, 4, 5, 6;
int[] thirdInner = outer[2];
other = null; // remove the reference


The situation is now



outer --> null

___> 1, 2
|
int[][] ---|---> 3, 4
|
|______> 5, 6
|
thirdInner _______________|


So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:



outer --> null
thirdInner --> 5, 6





share|improve this answer




















  • 3





    "Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

    – Boris the Spider
    15 hours ago











  • That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

    – Zabuza
    15 hours ago











  • @BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

    – bwoebi
    13 hours ago






  • 1





    "Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

    – Boann
    9 hours ago


















13














At some point after the array goes out of scope, the garbage collector will reclaim the memory if there are no other references to it.



If you want to null your reference before the variable goes out of scope (keep in mind that if some other code has this reference, it won't get garbage collected):



Foo[][] fooArray = new Foo[2][3];

...

// this will null the reference to the array
fooArray = null;





share|improve this answer




















  • 3





    Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

    – Konrad Rudolph
    16 hours ago












  • Good point - edited.

    – Jason
    3 hours ago


















2














Unlike C, Java provides automatic garbage collection,which will clear the array for you as it becomes unreachable(i.e goes out of scope).If you want you can make the array as null so that the memory location becomes unreachable.



 Foo[][] fooArray = new Foo[2][3];
.
.
.
fooArray = null;
System.gc();


This gc call doesn't ensure that JVM will run garbage collector but it suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects






share|improve this answer




















  • 3





    I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

    – Zabuza
    18 hours ago












  • I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

    – Vaibhav Gupta
    18 hours ago






  • 4





    @Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

    – Jonathan Rosenne
    17 hours ago

















3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









15














Explantion



You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either



  1. let the variable fall out of scope or

  2. assign null

  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.




References



To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector will delete anything which is not referenced. So let's take a look at an array such as:



int[][] outer = 1, 2, 3, 4, 5, 6;


We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:



 ___> 1, 2
|
outer --> int[][] ---|---> 3, 4
|
|___> 5, 6


So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.



Now assume that you would reference one of the inner arrays by another variable:



int[][] outer = 1, 2, 3, 4, 5, 6;
int[] thirdInner = outer[2];
other = null; // remove the reference


The situation is now



outer --> null

___> 1, 2
|
int[][] ---|---> 3, 4
|
|______> 5, 6
|
thirdInner _______________|


So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:



outer --> null
thirdInner --> 5, 6





share|improve this answer




















  • 3





    "Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

    – Boris the Spider
    15 hours ago











  • That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

    – Zabuza
    15 hours ago











  • @BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

    – bwoebi
    13 hours ago






  • 1





    "Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

    – Boann
    9 hours ago















15














Explantion



You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either



  1. let the variable fall out of scope or

  2. assign null

  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.




References



To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector will delete anything which is not referenced. So let's take a look at an array such as:



int[][] outer = 1, 2, 3, 4, 5, 6;


We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:



 ___> 1, 2
|
outer --> int[][] ---|---> 3, 4
|
|___> 5, 6


So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.



Now assume that you would reference one of the inner arrays by another variable:



int[][] outer = 1, 2, 3, 4, 5, 6;
int[] thirdInner = outer[2];
other = null; // remove the reference


The situation is now



outer --> null

___> 1, 2
|
int[][] ---|---> 3, 4
|
|______> 5, 6
|
thirdInner _______________|


So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:



outer --> null
thirdInner --> 5, 6





share|improve this answer




















  • 3





    "Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

    – Boris the Spider
    15 hours ago











  • That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

    – Zabuza
    15 hours ago











  • @BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

    – bwoebi
    13 hours ago






  • 1





    "Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

    – Boann
    9 hours ago













15












15








15







Explantion



You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either



  1. let the variable fall out of scope or

  2. assign null

  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.




References



To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector will delete anything which is not referenced. So let's take a look at an array such as:



int[][] outer = 1, 2, 3, 4, 5, 6;


We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:



 ___> 1, 2
|
outer --> int[][] ---|---> 3, 4
|
|___> 5, 6


So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.



Now assume that you would reference one of the inner arrays by another variable:



int[][] outer = 1, 2, 3, 4, 5, 6;
int[] thirdInner = outer[2];
other = null; // remove the reference


The situation is now



outer --> null

___> 1, 2
|
int[][] ---|---> 3, 4
|
|______> 5, 6
|
thirdInner _______________|


So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:



outer --> null
thirdInner --> 5, 6





share|improve this answer















Explantion



You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either



  1. let the variable fall out of scope or

  2. assign null

  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.




References



To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector will delete anything which is not referenced. So let's take a look at an array such as:



int[][] outer = 1, 2, 3, 4, 5, 6;


We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:



 ___> 1, 2
|
outer --> int[][] ---|---> 3, 4
|
|___> 5, 6


So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.



Now assume that you would reference one of the inner arrays by another variable:



int[][] outer = 1, 2, 3, 4, 5, 6;
int[] thirdInner = outer[2];
other = null; // remove the reference


The situation is now



outer --> null

___> 1, 2
|
int[][] ---|---> 3, 4
|
|______> 5, 6
|
thirdInner _______________|


So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:



outer --> null
thirdInner --> 5, 6






share|improve this answer














share|improve this answer



share|improve this answer








edited 17 hours ago

























answered 18 hours ago









ZabuzaZabuza

12.1k52744




12.1k52744







  • 3





    "Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

    – Boris the Spider
    15 hours ago











  • That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

    – Zabuza
    15 hours ago











  • @BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

    – bwoebi
    13 hours ago






  • 1





    "Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

    – Boann
    9 hours ago












  • 3





    "Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

    – Boris the Spider
    15 hours ago











  • That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

    – Zabuza
    15 hours ago











  • @BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

    – bwoebi
    13 hours ago






  • 1





    "Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

    – Boann
    9 hours ago







3




3





"Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

– Boris the Spider
15 hours ago





"Not referenced" is tricky - as everything is "not referenced" at some point. The correct language is "not reachable by hard references from a GC root".

– Boris the Spider
15 hours ago













That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

– Zabuza
15 hours ago





That's absolute correct and a good note! But I feel that it would unnecessarily complicate the answer.

– Zabuza
15 hours ago













@BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

– bwoebi
13 hours ago





@BoristheSpider I think "not referenced" is a good choice of words, as everything is referenced in java, just possibly not necessarily from java objects but from the jvm internals (e.g. stack variables, loaded java.lang.Class instances, ...) (the latter cases being marked together as GC roots). So I'd still call it "referenced".

– bwoebi
13 hours ago




1




1





"Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

– Boann
9 hours ago





"Not referenced" is not strictly correct. "Not referenced" implies that two objects which refer to each other, or one object which refers to itself, won't be deleted, which is obviously untrue. Garbage collectors don't delete objects that are "not referenced", they delete objects that are not reachable from a GC root (running thread). When null is assigned to outer, the entire array and all inner arrays become not reachable by the program, and all are swept away in one go. It's not necessary to delete the outer array first, in order to discover the inner arrays were also deletable.

– Boann
9 hours ago













13














At some point after the array goes out of scope, the garbage collector will reclaim the memory if there are no other references to it.



If you want to null your reference before the variable goes out of scope (keep in mind that if some other code has this reference, it won't get garbage collected):



Foo[][] fooArray = new Foo[2][3];

...

// this will null the reference to the array
fooArray = null;





share|improve this answer




















  • 3





    Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

    – Konrad Rudolph
    16 hours ago












  • Good point - edited.

    – Jason
    3 hours ago















13














At some point after the array goes out of scope, the garbage collector will reclaim the memory if there are no other references to it.



If you want to null your reference before the variable goes out of scope (keep in mind that if some other code has this reference, it won't get garbage collected):



Foo[][] fooArray = new Foo[2][3];

...

// this will null the reference to the array
fooArray = null;





share|improve this answer




















  • 3





    Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

    – Konrad Rudolph
    16 hours ago












  • Good point - edited.

    – Jason
    3 hours ago













13












13








13







At some point after the array goes out of scope, the garbage collector will reclaim the memory if there are no other references to it.



If you want to null your reference before the variable goes out of scope (keep in mind that if some other code has this reference, it won't get garbage collected):



Foo[][] fooArray = new Foo[2][3];

...

// this will null the reference to the array
fooArray = null;





share|improve this answer















At some point after the array goes out of scope, the garbage collector will reclaim the memory if there are no other references to it.



If you want to null your reference before the variable goes out of scope (keep in mind that if some other code has this reference, it won't get garbage collected):



Foo[][] fooArray = new Foo[2][3];

...

// this will null the reference to the array
fooArray = null;






share|improve this answer














share|improve this answer



share|improve this answer








edited 3 hours ago

























answered 18 hours ago









JasonJason

9,62733545




9,62733545







  • 3





    Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

    – Konrad Rudolph
    16 hours ago












  • Good point - edited.

    – Jason
    3 hours ago












  • 3





    Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

    – Konrad Rudolph
    16 hours ago












  • Good point - edited.

    – Jason
    3 hours ago







3




3





Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

– Konrad Rudolph
16 hours ago






Your phrasing (“once”) makes it sounds as if the memory will be reclaimed as soon as the last reference goes out of scope. It’s a rather important property of the Java GC that this is not the case.

– Konrad Rudolph
16 hours ago














Good point - edited.

– Jason
3 hours ago





Good point - edited.

– Jason
3 hours ago











2














Unlike C, Java provides automatic garbage collection,which will clear the array for you as it becomes unreachable(i.e goes out of scope).If you want you can make the array as null so that the memory location becomes unreachable.



 Foo[][] fooArray = new Foo[2][3];
.
.
.
fooArray = null;
System.gc();


This gc call doesn't ensure that JVM will run garbage collector but it suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects






share|improve this answer




















  • 3





    I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

    – Zabuza
    18 hours ago












  • I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

    – Vaibhav Gupta
    18 hours ago






  • 4





    @Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

    – Jonathan Rosenne
    17 hours ago















2














Unlike C, Java provides automatic garbage collection,which will clear the array for you as it becomes unreachable(i.e goes out of scope).If you want you can make the array as null so that the memory location becomes unreachable.



 Foo[][] fooArray = new Foo[2][3];
.
.
.
fooArray = null;
System.gc();


This gc call doesn't ensure that JVM will run garbage collector but it suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects






share|improve this answer




















  • 3





    I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

    – Zabuza
    18 hours ago












  • I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

    – Vaibhav Gupta
    18 hours ago






  • 4





    @Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

    – Jonathan Rosenne
    17 hours ago













2












2








2







Unlike C, Java provides automatic garbage collection,which will clear the array for you as it becomes unreachable(i.e goes out of scope).If you want you can make the array as null so that the memory location becomes unreachable.



 Foo[][] fooArray = new Foo[2][3];
.
.
.
fooArray = null;
System.gc();


This gc call doesn't ensure that JVM will run garbage collector but it suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects






share|improve this answer















Unlike C, Java provides automatic garbage collection,which will clear the array for you as it becomes unreachable(i.e goes out of scope).If you want you can make the array as null so that the memory location becomes unreachable.



 Foo[][] fooArray = new Foo[2][3];
.
.
.
fooArray = null;
System.gc();


This gc call doesn't ensure that JVM will run garbage collector but it suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects







share|improve this answer














share|improve this answer



share|improve this answer








edited 18 hours ago

























answered 18 hours ago









Vaibhav GuptaVaibhav Gupta

477311




477311







  • 3





    I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

    – Zabuza
    18 hours ago












  • I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

    – Vaibhav Gupta
    18 hours ago






  • 4





    @Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

    – Jonathan Rosenne
    17 hours ago












  • 3





    I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

    – Zabuza
    18 hours ago












  • I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

    – Vaibhav Gupta
    18 hours ago






  • 4





    @Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

    – Jonathan Rosenne
    17 hours ago







3




3





I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

– Zabuza
18 hours ago






I do not really see the benefit of suggesting System#gc. In most situations it will degrade performance. Let the garbage collector do it's job. It is usually only used to cleanup before a measurement (profiler and other tools).

– Zabuza
18 hours ago














I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

– Vaibhav Gupta
18 hours ago





I agree with you but in some cases, it may make sense to suggest to the JVM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy work

– Vaibhav Gupta
18 hours ago




4




4





@Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

– Jonathan Rosenne
17 hours ago





@Vaibhav Gupta The garbage collector does not clear the array, it only frees it. It is possible for malware to access the data, sometimes for a long time, until the memory has been reused. If the array contains sensitive data it should be actively cleared before being released.

– Jonathan Rosenne
17 hours ago



Popular posts from this blog

Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп

ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result