Object is storage and removal from heap memory - java

Can anybody explain to me how objects are stored and removed from heap memory of Java. I'm looking for more information than simply:
an Object will removed when there is no reference
For example:
class Heap
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String ar[])
{
Heap obj=new Heap();
obj.add(4,3);
obj.add(5,5);
}
}
Here how is obj and a, `bJ allocated in java memory. When will it be removed from memory by the JVM?

Put simply:
obj is allocated on the heap when new Heap() is invoked.
a and b both are allocated on the stack (primitive types, method arguments), the memory will be released upon returning from add.
obj will be removed from the heap whenever the garbage collector runs after the execution is out of main (the specification does not guarantee the GC will at any given time, it'll figure out when's the right time on its own, although almost-full-heap is probably a very common trigger) - in this case though, since the program would terminate, it would be immediately after returning from main.

The Heap object will be create inside heap. that will contain the methods inside the class and member variables.
when you call a method, that will be loaded inside stack and will be discarded automatically by jvm after executing that method.
Stack section of memory contains methods, local variables and reference variables.
Heap section contains Objects (may also contain reference variables).

Well... a and b aren't allocated on the heap at all.
They are on the stack for passing into the function. As soon as the execution leaves add(), the variables a and b cannot be used anymore and will be removed by the jvm.

When you run your program:
Before the main method is executed, the JVM will allocate a new thread of execution for you, this thread (called the main thread) will have a stack associated with it, the stack is a place where local variables and temporary data is placed.
Within the stack a new frame will be associated with the main method.
The obj reference will be created in the main method stack frame.
When you invoke the new Heap() the JVM will attempt to allocate memory for your object in the heap memory area. If successful, it will assign an object reference to your local variable, if it fails, it may attempt to make room for your object running the garbage collector, if still fails to find enough room for it an OutOfMemoryError is thrown.
When you invoke the add(int, int) method on your memory reference, the JVM will first dereference the pointer to gain access to the actual object in the heap, if it fails a NullPointerException will be thrown, otherwise it will look for the method to be executed in what is called the method area (an area of memory where class information is located).
If the method is found, a new frame is created in the in the stack of the currently executing thread, and the control of execution is transferred to the new method.
Two variables are placed in the method stack frame a and b and they are initialized with copies of the values you passed as arguments (i.e. 4, 3).
The method does what it does, and when it is done the current stack frame is destroyed, and control of execution returns to the previous frame.
Since you invoke the method add again, the process is repeated.
The main method ends, its stack frame is removed. Now the obj reference is lost and there is no longer a way to reach to your object in the heap. The object it was pointing to is now illegible for garbage collection.
The JVM process is terminated and all related resources are freed. Probably in this scenario, the garbage collection actually never run, but if it did, the memory occupied by your object in the heap would be reclaimed.

Related

How Java manages variables in memory

Let's say I have this code:
{
int var = 2;
// more code
}
What happens with 'var' after the code is executed and it is not used anymore? Is it deleted from memory or it stays there occupying memory, or something else?
Related to this, is it better to work with variables that way^, or to make some global variable and just change it's value?
Local variables live on the stack. If it's a reference to an object then only variable is on the stack.
Instance variables live on the heap because they belong to an object.
Also this post (Stack and heap memory in java) might be helpful.
To make a long story short, in java (and other JVM languages), you don't have to care about memory allocation and dealocation at all. You really shouldn't be worrying about it. Once you lose the reference to that variable (in this case, when the method call ends), the variable is effectively gone. Some indefinite amount of time after that, the Garbage collecting thread will notice that you can't possibly access that variable anymore, and free up the memory it was using.
See: Garbage Collection in Java.
if you are defining any variable as instance variable then that variable will be used by instance. and instance will be saved in Heap memory area.
Garbage collector will run periodically to clean non referenced object from memory.
but if that variable is defined inside any block or method then that will be stored Stack memory.
Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
Everything in Java is removed from memory when it is no longer referenced. It takes a lot of effort to cause true memory leaks in Java.
Java primitives like int, boolean, and char are put on the stack and removed from memory as soon as they leave scope. Java objects like String, arrays, or ArrayList are allocated on the heap (and referenced by the local variable on the stack). Objects are garbage collected (removed from memory) when there is no longer a reference to them.Static variables belong to a class and will be a reference an object as long as the class is loaded, which is usually the entire run time of the Java program. Statics are the closest thing Java has to global variables, but overuse or misuse of statics is actually a way to cause memory issues rather than solve them.

What occurs when object is created in Java?

My teacher gave me a question:
"What occurs when objects are created in Java".
To the best of my knowledge, memory allocation, variable initialization and constructor method invocation happen when an object is created.
But my teacher said that I was almost right. The 2 later things are right, except memory heap. Instead, he said the memory allocation occurs. I think that object is stored in heap, so my teacher is wrong. Do you think so?
As always, the best place to find a solution for these kinds of questions is in the Java Language Specification.
Specifically, from the section on new instance creation, it can be understood that this is the sequence when a new object is created, as long as no exceptions occur:
Memory is allocated.
Fields are initialized to their default values.
The "first line" of the chosen constructor is invoked, unless it's an Object. By first line I mean either explicit call to super() or this(), or an implicit call to super().
The instance initializer is executed and the fields are initialized to their requested values (actually field initialization is usually compiled as an inline part of the instance initializer).
The rest of the constructor code is executed.
Now, it is possible that your teacher is talking about memory allocation as an actual operating system call - and in that case he's right in the sense that the JVM manages its own heap and thus a Java memory allocation does not necessarily translate to an OS memory allocation call (although it may).
I'll answer that using a simple example.
Say you have a class Car. Now you write:
Car car;
car = new Car();
The first statement creates a reference with car in the stack.
In the second statement, the Car class will be loaded to the main memory, then it will allocate memory for the members of Car in the heap. When this happens, the members will be initialized with values provided by the JVM.
While the JVM is running the program, whenever a new object is created, the JVM reserves as portion of the Heap for that object (where the object will be stored). The amount of Heap that gets reserved is based on the size of the object.
The JVM maps out this segment in the Heap to represent all of the attributes of the object being stored. A reference (address in Heap) to the object is kept by the JVM and stored in a table that allows the JVM to keep track of all the objects that have been allocated on the Heap. The JVM uses these references to access the objects later (when the program accesses the object).
On top of what other people have said, if this is the first use of the object then its Class must be initialised -as described in the JLS (the section before the one on new instance creation!).
This basically involves loading into memory the necessary information about the class i.e. creating a Klass object for the static variables and method table to live. This may also involve loading super classes and interfaces. This is all carried out by the ClassLoader.
When object is created in java then these 6 step will be happens one by one---
1.JVM allocates 8 bytes of memory for the reference variable & assign default value as null.
JVM will verify whether class loading is done or not,if class is already loaded then it will ignore or else it will perform class loading.
At the time of class loading ,if any static variable are there then it will allocating memory.
By using new operator,object memory will e created inside heap memory.
At the time of object creation,if any instance variables are there then those will allocate memory inside object Memory.
It will assign object memory address to the reference variable which is created first.

Java memory (Stack) allocation for local variables

I am learning java and right now
i am stuck at memory allocation of object's and local variables.
can any one illustrate or clear some of my doubts??
I read about Heap and Stack Memory for Object's instance
Variable's and Local Variable's. I have question whether a new
STACK is being created for each method?? or for each class of a
single stack is used by a whole class??
I had read that ONE STACK
is being created by every thread What is means
Thanks
Mahaveer
Every thread has it's own stack.
Whenever you use new, an object is created on the heap.
Local variables are stored on the stack. That includes primitives (such as int) and the references to any objects created. The actual objects themselves aren't created on the stack, as I mentioned when you use new they'll be created on the heap.
I have question that weather a new STACK is being created for each
method??
The same stack is being used when a method is called. A method will create it's own little section on the stack called a "stack frame" that's used to hold it's local variables.
It's just like a stack of plates, when a method is called a plate is added to the top of the stack (a stack frame), and when that method ends the plate is removed from the stack. All of that method's local variables will be destroyed with it, but the actual objects created with new won't.
The JVM's garbage collector will look after destroying objects on the heap (the one's created with new) when it sees you no longer need them.
Each thread has a private stack.
Each method has a private stack frame within that thread's stack.
Stacks are associated with thread in a one-to-one mapping. Stacks are absolutely not associated with methods and classes.
The way to reason about all this is that the local variables of a method are private to each invocation of that method.
Ofcourse, java garbage collector always takes care of the Heap, when it gets a chance to be executed, so it only looks for orphan objects and wipes them out, that's why NEW keyword in java always creates new objects on the Heap memory.

android java memory management

how are static method calls handled by the JVM? does it still allocate memory when a call is made? if yes, how does garbage collection treat this allocation after the method call?
What do you mean by allocate memory? Does it add a stack frame? yes of course, to run the method and allocate local variable storage. Static methods are no different. In fact they're identical except instance methods are invisibly passed this in the method call, behind the scenes.
Any objects that were allocated in the method, and are no longer reachable after the method terminates (perhaps because they were only referred to by a local reference, local to the method) become eligible for GC immediately. There are no guarantees as to when the GC will run though.
But again that's no different for static methods than for any other.

Can using too many static variables cause a memory leak in Java?

If my application has too many static variables or methods, then as per definition they will be stored in heap. Please correct me if I am wrong
1) Will these variables be on heap until application is closed?
2) Will they be available for GC at any time? If not can I say it is a memory leak?
Static methods are just methods, they are not stored on the heap, they just don't get to use a "this" parameter.
Static variables serve as "roots" to the GC. As a result, unless you explicitly set them to null, they will live as long as the program lives, and so is everything reachable from them.
A situation is only considered a memory leak if you intend for the memory to become free and it doesn't become free. If you intend for your static variable to contain a reference to an object for part of the time, and you forget to set it to null when you're done with that object, you would likely end up with a leak. However, if you put it in the static variable and intend for it to be there for as long as the program is running, then it is most definitely not a leak, it is more likely a "permanent singleton". If the object got reclaimed while you wanted it to still exist, that would have been very bad.
As for your question about the heap: All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object.
If you have a static hashmap and you add data to it... the data will never disappear and you have a leak - in case you do not need the data anymore. If you need the data, it is not a leak, but a huge pile of memory hanging around.
Objects directly or indirectly referenced by statics will remain on the heap until the appropriate class loader can be collected. There are cases (ThreadLocal, for instance) where other objects indirectly reference the class loader causing it to remain uncollected.
If you have a static List, say, and add references to it dynamically, then you can very easily end up with "object lifetime contention issues". Avoid mutable statics for many reasons.
As long as you can reference these variables from somewhere in the code it can't by GCed which means that they will be there until the end of the application.
Can you call it a memory leak, I wouldn't call it a memory leak, usually a memory leak is memory that you normally expect to recover but you never do, or you only recover part of it. Also memory leaks usually get worse in time (eg: every time you call a method more memory is "leaked") however in this case the memory usage for those variables is (kind of) static.
It won't cause a memory leak in the classic C sense... For example
Class A{
static B foo;
...
static void makeFoo(){
foo = new B();
foo = new B();
}
In this case, a call to makeFoo() won't result in a memory leak, as the first instance can be garbage collected.

Categories