June 1st, 2011, 01:09 AM
Assigning null to Complex Type object in the context of memory in java
What is the meaning of assigning null to Complex Type object in the context of memory in java language.
while(true) //Approx 9000 times
Employee objEmployee = new Employee ();
objEmployee = //Put some value
objEmployee = null;
Does assigning null to the complex type make the object ready for garbage collection in java.Also
is it the way to efficient memory management in java.
June 1st, 2011, 04:13 AM
Re: Assigning null to Complex Type object in the context of memory in java
Assigning null to an object variable is just nulling a reference to that object. In general, an object becomes eligible for garbage collection when it is no longer reachable, i.e. there are no more usable/active references to it. When all references to an object are null or have gone out of scope, it becomes unreachable. This is a somewhat rough generalisation, as there are different strengths of references (e.g. 'weak' references that may be 'soft' or 'phantom') that are each treated slightly differently, but the principle is correct. Eligibility for garbage collection is no guarantee that the object will be collected. If there is sufficient memory, eligible objects may never be GC'd - it depends on the GC implementation.
There are lots of articles about this online - check out IBM's Java Memory Management Guide.
Generally, if you're writing well-structured code and following good guidelines, it isn't necessary to null references after use. However, there are areas that a coder needs to be aware of that can be problematic, such as collections and static variables, and especially static collections. Items added to a static list will remain there and ineligible for garbage collection until removed or until the list is explicitly nulled. If such items are large, complex objects (e.g. GUI frames), a major chunk of the application may be rendered inelligible for GC. The same problem may occur if small items containing references to large, complex items are stored in collections or are member variables of long-lived objects.
640K [of main memory] ought to be enough for anybody...
Bill Gates (disclaimed)
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!