Memory allocation of new object
Hello,
I have a beginners question for you
If I make 2 "new" on the same variable:
Example
Code:
byte[] b = new byte[sz + 100];
...
.../ / code ...
...
b = new byte[sz];
Is that space that was allocated in memory with the first "new", be well removed by the garbage collector before the second allocation? Or is it going to be a conflict because the variable has 2 memory addresses? How the memory is allocated for the new object? Any help on this is appreciated. Thanks in advance.
Re: Memory allocation of new object
Hello,
The memory allocated in the first "new" will be removed after the second allocation when the garbage collector will run. In fact you can not really knowing where the Garbage collector reclaim memory. An object is de-allocated when no longer affiliated with the objects in your application. Here seen as "buff" points to the second allocation, the first may be recovered by the Garbage collector.
Re: Memory allocation of new object
Hello,
There will be no conflict if two byte [] are allocated. What you do by
during your second benefit is that you allocate a new memory for your object, you associate him the reference b. The first allocation was no longer of reference and will be thrown in the trash by the garbage collector. If you need any more help regarding this topic then you can ask and we will try to solve your query.
Re: Memory allocation of new object
Hello,
That's right, when an object no longer reference it, it is touchy to be the part of the work by the garbage collector. You can not really know when, even if it is possible to explicitly call the garbage collector using the method
Code:
System.gc () (use only in rare cases very specifically)
If you need more information on the garbage collector then you can visit the sun's official site there you can find more detailed information on the garbage collector.
Re: Memory allocation of new object
Hello,
This is possible with Reference and ReferenceQueue (read: Understanding References in Java). I would say especially not to use: In the best case it will do nothing, but he runs it causes a full collection ", i.e a release of up to object but can be quite costly in execution time. Using massively (in a loop for example), this can give disastrous results, for example: Difference of performance Unix / Windows program? In short, the de-allocation is done automatically by the garbage collector, and the best thing to do is let it work in his corner.
Re: Memory allocation of new object
Hello,
I do not know that this is what you need exactly, but here is a code, see if it can help you.
Code:
public class SomeObject{
private String str;
public SomeObject(String str){
this.str = str;
}
public void setSomeProperty(String str){
this.str = str;
}
public String getSomeProperty(){
return this.str;
}
}