2. Memory handling in Java
Java handles its memory in two areas. The heap and the stack. We will start with a short overview of memory in general on a computer. Then the Java heap and stack is explained.
Native memory is the memory which is available to a process, e.g. the Java process. Native memory is controlled by the operating system (OS) and based on physical memory and other physical devices, e.g. disks, flash memory, etc.
The processor (CPU) of the computer computes the instructions to execute and stores its computation results into registers. These registers are fast memory elements which stores the result of the CPU. The processor can access the normal memory over the memory bus. A amount of memory a CPU can access is based on the size of the physical address which the CPU uses to identify physical memory. A 16-bit address can access 2^16 (=65.536) memory locations. A 32-bit address can access 2^32 (=4.294.967.296) memory locations. If each memory area consists of 8 bytes then a 16-bit system can access 64KB of memory and the 32-bit system can access 4GB of memory.
An operating system (OS) normally uses virtual memory to map the physical memory to memory which each process can see. The OS assigns then memory to each process in a virtual memory space for this process and maps access to this virtual memory to the real physical memory.
Current 32-bit systems uses an extension (Physical Address Extension (PAE)) which extends the physical space to 36-bits of the operation system. This allows the OS to access 64GB. The OS uses then virtual memory to allow the individual process 4 GB of memory. Even with PAE enabled a process can not access more then 4 GB of memory.
Java manages the memory for use. New objects created and placed in the heap. Once your application have no reference anymore to an objects the Java garbage collector is allowed to delete this object and remove the memory so that your application can use this memory again.
In the heap the Java Virtual Machine (JVM) stores all objects created by the Java application, e.g. by using the "new" operator. The Java garbage collector (gc) can logically separate the heap into different areas, so that the gc can faster identify objects which can get removed
The memory for new objects is allocated on the heap at run time. Instance variables live inside the object in which they are declared.
Heap in Java generally located at bottom of address space and move upwards. whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java, to learn more about garbage collection see how garbage collection works in Java.
Stack is where the method invocations and the local variables are stored. If a method is called then its stack frame is put onto the top of the call stack. The stack frame holds the state of the method including which line of code is executing and the values of all local variables. The method at the top of the stack is always the current running method for that stack. Threads have their own call stack.
As stated earlier Java objects are created and stored in the heap. The programming language does not offer the possibility to let the programmer decide if an objects should be generated in the stack. But in certain cases it would be desirable to allocate an object on the stack, as the memory allocation on the stack is cheaper then the memory allocation in the heap, deallocation on the stack is free and the stack is efficiently managed by the runtime.
The JVM uses therefore internally escape analysis to check if an object is used only with a thread or method. If the JVM identify this it may decide to create the object on the stack, increasing performance of the Java program.
Garbage Collector
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any live references in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will beeligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.
Question 2 - How do you identify minor and major garbage collection in Java?
Answer: Minor collection prints “GC” if garbage collection logging is enable using –verbose:gc or -XX:PrintGCDetails, while Major collection prints “Full GC”.
ParNew and DefNew is two young generation garbage collector. ParNew is a multi-threaded GC used along with concurrent Mark Sweep while DefNew is single threaded GC used along with Serial Garbage Collector.
finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc
JAVA HEAP DUMP:
http://java.dzone.com/articles/java-heap-dump-are-you-task
PermGen space is used to store class’s metadata and filling of PermGen space can cause java.lang.OutOfMemory:PermGen space.
Memory Questions:
1. what is gc?
Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection
2. when is gc performed?
it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
3. Can we invoke gc manually?
We can not force gc, but we can use System.gc() and Runtime.gc() to send request of gc to JVM, but it is not guaranteed.
4. how does jvm manage its memory?
New objects created and placed in the heap. Once your application have no reference anymore to an objects the Java garbage collector is allowed to delete this object and remove the memory so that your application can use this memory again.
In the heap the Java Virtual Machine (JVM) stores all objects created by the Java application, e.g. by using the "new" operator. The Java garbage collector (gc) can logically separate the heap into different areas, so that the gc can faster identify objects which can get removed
Stack is where the method invocations and the local variables are stored
5. what is memory leak?
when a computer program consumes memory but is unable to release it back to the operating system.In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code
6. does java have memory leak, can you explain or give an example?
These leaks are caused by the code/programmer keeping references to objects which are technically no longer needed.These leaks are caused by completely losing access to chunks of memory without marking them as unused.In Java this occurs when you forget to set references to null.
in some situations, when the object is no longer in use, but some references to that object has not been removed. This kind of objects will not be collected by the garbage collector. That means there is a memory leak. Sometimes memory leaks in Java is also referred to as "dangling references".
看了众多资料 还是不太懂这是个什么情况。object不在用了 但是还有reference, 有这种情况吗? 还有就是如果一个program 包含许多object reference,超过memory limit 算 memory leak吗?
7. what is heap dump?
heap dump is basically a “snapshot” of the Java heap memory at a given time
Such snapshot contains low level detail about the java objects and classes allocated on the Java heap such as:
· Java objects such as Class, fields, primitive values and references
· Classloader related data including static fields (important for classloader leak problems)
· Garbage collection roots or objects that are accessible from outside the heap (System classloader loaded resources such as rt.jar, JNI or native variables, Threads, Java Locals and more…)
· Thread related data & stacks (very useful for sudden Java heap increase problems, especially when combined with thread dump analysis)
JVM heap dumps are typically generated as a result of 2 actions:
· Auto-generated or triggered as a result of a java.lang.OutOfMemoryError (e.g. Java Heap, PermGen or native heap depletion)
· Manually generated via the usage of tools such as jmap, VisualVM (via JMX) or OS level command
8. what is thread dump?
A thread dump is a list of all the Java threads that are currently active in a Java Virtual Machine
this is especially useful if your Java application sometimes seems to hang when running under load, as an analysis of the dump will show where the threads are stuck.
You can generate a thread dump under Unix/Linux by running kill -QUIT <pid>, and underWindows by hitting Ctl + Break.