1. Difference between JRE JVM and JDK?
Java Virtual Machine (JVM)
The Java Virtual Machine (JVM) is the virtual machine that runs the Java bytecodes. The JVM doesn't understand Java source code; that's why you compile your *.java files to obtain *.class files that contain the bytecodes understood by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed, there are specific implementations of the JVM for different systems (Windows, Linux, macOS, see the Wikipedia list), the aim is that with the same bytecodes they all give the same results.
Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.
Java Development Kit (JDK)
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
2. What is the difference between the source code found in the OpenJDK repository, and the code you use to build the Oracle JDK?
It is very close - our build process for Oracle JDK releases builds on OpenJDK 7 by adding just a couple of pieces, like the deployment code, which includes Oracle's implementation of the Java Plugin and Java WebStart, as well as some closed source third party components like a graphics rasterizer, some open source third party components, like Rhino, and a few bits and pieces here and there, like additional documentation or third party fonts. Moving forward, our intent is to open source all pieces of the Oracle JDK except those that we consider commercial features such as JRockit Mission Control (not yet available in Oracle JDK), and replace encumbered third party components with open source alternatives to achieve closer parity between the code bases.
3. How to fix Invalid initial and maximum heap size in JVM?
This cause mainly because of memory initilization. Please find the following usecases
java -Xmx4056M -Xms4056M HelloWorld
Issue: Error occurred during initialization of VM , The size of the object heap + VM data exceeds the maximum representable size
java -Xmx1056M -Xms2056M HelloWorld
Issue: Error occurred during initialization of VM , Incompatible minimum, and maximum heap sizes specified
Cause: value of -Xms is higher than -Xmx
java -Xms2056M HelloWorld
Issue: Error occurred during initialization of VM , Could not reserve enough space for object heap
Cause: Only -Xms was provided and -Xmx was not provided. you will also get this error if you have a typo and instead of -Xmx you have specified -Xms two times, happened to my friend last time.
Command: java -Xms1024 M -Xmx1024M HelloWorld
Issue: Error occurred during initialization of VM , Too small initial heap
Cause: If you had space between 1024 and M than JVM assumes the size of -Xms as 1024 bytes only and print error that it's too small for JVM to start.
4. What is classloader?
What is ClassLoader in Java
ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader.
Every class loader has a predefined location, from where they loads class files. Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null and any code based on that may throw NullPointerException in Java. Bootstrap class loader is also known as Primordial ClassLoader in Java.
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader.
Third default class loader used by JVM to load Java classes is called System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR. Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class. Also, except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader.
In short here is the location from which Bootstrap, Extension and Application ClassLoader load Class files.
- Bootstrap ClassLoader - JRE/lib/rt.jar
- Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
- Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.
5. How a Java Class Loader Works?
When a class name is given, class loader first locates the class and then reads a class file of that name from the native file system. Therefore this loading process is platform dependent.
By default java.lang.ClassLoader is registered as a class loader that is capable of loading classes in parallel. But the subclasses needs to register as parallel or not at the time of instantiation.
Classes can also be loaded from network, constructed on runtime and loaded. ClassLoader class has a method name defineClass which takes input as byte array and loads a class.
Class Loader Parent
All class loaders except bootstrap class loader has a parent class loader. This parent is not as in parent-child relationship of inheritance. Every class loader instance is associated with a parent class loader.
When a class loader is entrusted with the responsibility of loading a class, as a first step it delegates this work to the associated parent class loader. Then this parent class loader gets the instruction and sequentially it delegates the call to its parent class loader. In this chain of hierarchy the bootstrap class loader is at the top.
When a class loader instance is created, using its constructor the parent classloader can be associated with it.
6. List some JVM Hotspot options?
1) JVM memory options related to java heap size
Following three JVM options are used to specify initial and max heap size and thread stack size while running Java programs
- -Xms set initial Java heap size
- -Xmx set maximum Java heap size
- -Xss set java thread stack size
2) JVM option to print gc details
-verbose:gc logs garbage collector runs and how long they're taking. I generally use this as my first tool to investigate if GC is a bottleneck for a given application.
-XX:+PrintGCDetails includes the data from -verbose:gc but also adds information about the size of the new generation and more accurate timings.
-XX:-PrintGCTimeStamps Print timestamps at garbage collection.
3) JVM parameters to specify Java Garbage collector
- -XX:+UseParallelGC Use parallel garbage collection for scavenges
- -XX:-UseConcMarkSweepGC Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)
- -XX:-UseSerialGC Use serial garbage collection. (Introduced in 5.0.)
beware when you use GC Parameters if you are working on time critical application e.g. high frequency trading application. As GC is time consuming operation and its desired to create a balance.
4) JVM debug options JVM options for remote debugging
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
5) JVM options related to profiling
- -Xprof
- -Xrunhprof
6) JVM options related to java classpath
Xbootclasspath specifies classpath entries you want loaded without verification. The JVM verifies all classes it loads to ensure they don't try to dereference an object with an int, pop extra entries off the stack or push too many, and so on. This verification is part of the reason why the JVM is very stable, but it's also rather costly, and responsible for a large part of start up delay. Putting classes on the bootclasspath skips this cost, but should only be used when you know the classes have been verified many times before. In JRuby, this reduced startup time by half or more for a simple script. The -Xbootclasspath option can be used to either prepend (/p) or append (/a) resources to the bootstrap classpath. You Can read more about Java Classpath in my articles How Classpath Works in Java and How to Solve ClassNotFoundException in Java
7) JVM options to change Perm Gen Size
These JVM optiosn are quite useful to solve java.lang.OutOfMemoryError:Perm Gen Space.
- -XX:PermSize and MaxPermSize
- -XX:NewRatio=2 Ratio of new/old generation sizes.
- -XX:MaxPermSize=64m Size of the Permanent Generation.
8) JVM parameters to trace classloading and unloading
-XX:+TraceClassLoading and -XX:+TraceClassUnloading are two JVM options which we use to print logging information whenever classes loads into JVM or unloads from JVM. These JVM flags are extremely useful if you have any memory leak related to classloader and or suspecting that classes are not unloading or garbage collected.
9) JVM switches related to logging
-XX:+TraceClassLoading and -XX:+TraceClassUnloading print information class loads and unloads. Useful for investigating if you have a class leak or if old classes (like JITed Ruby methods in JRuby) are getting collected or not. You can read more about logging in Java on my post 10 Tips while logging in Java
-XX:+PrintCompilation prints out the name of each Java method Hotspot decides to JIT compile. The list will usually show a bunch of core Java class methods initially, and then turn to methods in your application. In JRuby, it eventually starts to show Ruby methods as well
10) JVM Switches for debugging purpose
- -XX:HeapDumpPath=./java_pid.hprof Path to directory or file name for heap dump.
- -XX:-PrintConcurrentLocks Print java.util.concurrent locks in Ctrl-Break thread dump.
- -XX:-PrintCommandLineFlags Print flags that appeared on the command line.
That’s all on JVM Options, I understand its not possible to remember all JVM flags but at-least having an idea of what kind of JVM flags are available is good asset. Image for JVM parameters is from Java tuning and Nutshell. For full list of JVM options you can refer these link from Oracle Java site: Java Hotspot VM Options
7. What is Perm Gen space in Heap ?
Heap is divided into different generation e.g. new generation, old generation and PermGen space.PermGen space is used to store class’s metadata and filling of PermGen space can cause java.lang.OutOfMemory:PermGen space. Its also worth noting to remember JVM option to configure PermGen space in Java.
What are the difference between Eden Space, Survivor Space, Tenured Generation?
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
8. What are the different types of garbage collection in heap?
Minor GC
Collecting garbage from Young space (consisting of Eden and Survivor spaces) is called a Minor GC. This definition is both clear and uniformly understood. But there are still some interesting take-aways you should be aware of when dealing with Minor Garbage Collection events:
- Minor GC is always triggered when JVM is unable to allocate space for a new Object, e.g. the Eden is getting full. So the higher the allocation rate, the more frequently Minor GC is executed.
- Whenever the pool is filled, its entire content is copied and the pointer can start tracking the free memory from zero again. So instead of classical Mark, Sweep and Compact, cleaning Eden and Survivor spaces is carried out with Mark and Copy instead. So, no fragmentation actually takes place inside Eden or Survivor spaces. The write pointer is always residing on the top of the used pool.
- During a Minor GC event, Tenured generation is effectively ignored. References from tenured generation to young generation are considered de facto GC roots. References from young generation to Tenured generation are simply ignored during the markup phase.
- Against common belief, all Minor GCs do trigger stop-the-world pauses, stopping the application threads. For most of the applications, the length of the pauses is negligible latency-wise. This is true if most of the objects in Eden can be considered garbage and are never copied to Survivor/Old spaces. If the opposite is true and most of the newborn objects are not eligible for GC, Minor GC pauses start taking considerably more time.
Major GC vs Full GC
One should notice that there is no formal definitions present for those terms. Neither in JVM specification nor in the Garbage Collection research papers. But on the first glance, building these definitions on top of what we know to be true about Minor GC cleaning Young space should be simple:
Major GC is cleaning the Tenured space.
Full GC is cleaning the entire Heap – both Young and Tenured spaces.
Unfortunately it is a bit more complex and confusing. To start with – many Major GCs are triggered by Minor GCs, so separating the two is impossible in many cases. On the other hand – many modern garbage collections perform cleaning the Tenured space partially, so again, using the term “cleaning” is only partially correct.
This leads us to the point where instead of worrying whether the GC is called Major or Full GC, you should focus to finding out whether the GC at hand stopped all the application threads or was it able to progress concurrently with the application threads.
This confusion is even built right into the JVM standard tools. What I mean by that is best explained via an example. Lets compare the output of two different tools tracing the GC on a JVM running with Concurrent Mark and Sweep collector (-XX:+UseConcMarkSweepGC)
9. How do you identify minor and major garbage collection in Java?
Minor collection prints “GC” if garbage collection logging is enable using –verbose:gc or -XX:PrintGCDetails, while Major collection prints “Full GC”.
10. What is difference between ParNew and DefNew Young Generation Garbage collector?
By the way 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.
11. What is difference between Serial and Throughput Garbage collector?
Serial Garbage collector is a stop the world GC which stops application thread from running during both minor and major collection. Serial Garbage collector can be enabled using JVM option -XX:UseSerialGC and it's designed for Java application which doesn't have pause time requirement and have client configuration. Serial Garbage collector was also default GC in JDK 1.4 before ergonomics was introduced in JDK 1.5. Serial GC is most suited for small application with less number of thread while throughput GG is more suited for large applications. On the other hand Throughput garbage collector is parallel collector where minor and major collection happens in parallel taking full advantage of all the system resources available like multiple processor. Though both major and minor collection runs on stop-the-world fashion and introduced pause in application. Throughput Garbage collector can be enable using -XX:UseParallelGC
or -XX:UseOldParallelGC
. It increases overall throughput of application my minimizing time spent in Garbage collection but still has long pauses during full GC.
12. When does an Object becomes eligible for Garbage collection in Java ?
An object becomes eligible for garbage collection when there is no live reference for that object or it can not be reached by any live thread. Cyclic reference doesn’t count as live reference and if two objects are pointing to each other and there is no live reference for any of them, than both are eligible for GC. Also Garbage collection thread is a daemon thread which will run by JVM based upon GC algorithm and when runs it collects all objects which are eligible for GC.
13. What is finalize method in Java?
1) finalize() method is defined in java.lang.Object class, which means it available to all the classes for the sake of overriding. finalize method is defined as protected which leads to a popular core java question "Why finalize is declared protected instead of public"? well, I don't know the exact reason its falls in the same category of questions like why java doesn't support multiple inheritance which can only be answered accurately by designers of Java. any way making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.
2) One of the most important points of finalize method is that it's not automatically chained like constructors. If you are overriding finalize method then it's your responsibility to call finalize() method of the superclass, if you forgot to call then finalize of super class will never be called. so it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup. The best way to call superclass finalize method is to call them in the finally block as shown in below example. This will guarantee that finalize of the parent class will be called in all condition except when JVM exits:
@Override protected void finalize() throws Throwable { try{ System.out.println("Finalize of Sub Class"); //release resources, perform cleanup ; }catch(Throwable t){ throw t; }finally{ System.out.println("Calling finalize of Super Class"); super.finalize(); } }
3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like a normal method.
4) finalize gets called only once by GC thread if object revives itself from finalize method than finalize will not be called again.
5) Any Exception is thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact, I doubt if you find any trace of it.
6) There is one way to increase the probability of running of finalize method by calling System.runFinalization() and
Runtime.getRuntime().runFinalization()
. These methods put more effort that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called. It's not guaranteed, but JVM tries its best.
14. How Garbage Collection works in java?
1) Objects are created on the heap in Java irrespective of their scope e.g. local or member variable. while it's worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
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 an 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 a new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
15. Can we force Garbage collector to run at any time ?
No, you can not force Garbage collection in Java. Though you can request it by calling Sytem.gc()
or its cousin Runtime.getRuntime().gc()
. It’s not guaranteed that GC will run immediately as result of calling these method.
16. how to monitor garbage collection activities?
You can monitor garbage collection activities either offline or real-time. You can use tools like JConsole and VisualVM VM with its Visual GC plug-in to monitor real time garbage collection activities and memory status of JVM or you can redirect Garbage collection output to a log file for offline analysis by using -XlogGC=<PATH> JVM parameter. Anyway you should always enable GC options like -XX:PrintGCDetails -X:verboseGC and -XX:PrintGCTimeStamps as it doesn't impact application performance much but provide useful states for performance monitoring.
17. When a class is loaded and initialized in JVM?
When Class is loaded in Java
Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.
When a Class is initialized in Java
After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :
- an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
- an static method of Class is invoked.
- an static field of Class is assigned.
- an static field of class is used which is not a constant variable.
- if Class is a top level class and an assert statement lexically nested within class is executed.
Reflection can also cause initialization of class. Some methods of java.lang.reflect package may cause class to be initialized. JLS Strictly says that a class should not be initialized by any reason other than above.
Here are some of the rules of class initialization in Java:
- Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
- Super Class is initialized before Sub Class or derived class in Java
- If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type of Sub Class, Sub Interface or by implementation class of interface.
- interface initialization in Java doesn't cause super interfaces to be initialized.
- static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.
- non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.
18. Java ArrayList and HashMap Performance Improvement in JDK 7?
java.util.ArrayList code from JDK 1.6.30
Here is the code snippet from java.util.ArrayList
class from jdk1.6.30 to create an empty ArrayList :
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }
You can see that it's calling another constructor of java.util.ArrayList with initial capacity 10, which allocates array.
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }
java.util.ArrayList code from JDK 1.7.0._40
This version of ArrayList has an empty shared array, a static variable which is shared by all instances of ArrayList class.
/** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {};
and now look at the change made in no-argument constructor of java.util.ArrayList class
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; }
You can see that, instead of constructor chaining, elementDate is assigned an empty array. This immediately save memory hogged by an object array of size 10. By the way, how many of you have noticed the same comment "Constructs an empty list with an initial capacity of ten/" in both the version? Yes, they forget to update the comment, and that's one of the reason, why code comments are bad? they quickly loss relevance, as no compiler is there to verify correctness of a comment.
In Short
when you create empty ArrayList, without specifying any initial capacity i.e. by using new ArrayList(), Java creates an Object array of default size 10 to hold objects. This memory is allocated eagerly, even before you have added any object, which means, if 100K list is created during application runtime, say for storing order details of each order in a transaction processing system, and 10% of them will remain empty than you are going to lose significant memory.
By the way, it's not just memory, it’s also extra work-load for Garbage collector. If you are working in high frequency trading application development, where every ounce of performance matters or just care enough for performance of your Java application, you will appreciate this saving.
19. What is -XX:+UseCompressedOops in 64 bit JVM?
-XX:+UseCompressedOops
JVM option neutralizes penalty imposed by 64 bit JVM. By using -XX:+UseCompressedOops you can avail the benefit of both 64 bit JVM in terms of larger Java heap size and 32 bit JVM in terms of the compressed size of OOPS which results in better performance by utilizing CPU cache better than larger, space inefficient 64 bit OOPS pointers.
20. How to find CPU and Memory used by Java process?
1. Find the PID of Java process
ps -ef | grep "MyJavaSever"
2) Find CPU and Memory usage of Java process
prstat -p 28983 5 PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP 29389 appsvs 1129M 445M sleep 47 4 0:03:44 0.0% java/49
21. How to increase heap size in Java?
Default size of Heap space in Java is 128MB on most of 32 bit Sun's JVM but its highly varies from JVM to JVM e.g. default maximum and start heap size for the 32-bit Solaris Operating System (SPARC Platform Edition) is -Xms=3670K and -Xmx=64M and Default values of heap size parameters on 64-bit systems have been increased up by approximately 30%.
Also, if you are using throughput garbage collector in Java 1.5 default maximum heap size of JVM would be Physical Memory/4 and default initial heap size would be Physical Memory/16. Another way to find default heap size of JVM is to start an application with default heap parameters and monitor in using JConsole which is available on JDK 1.5 onwards, on VMSummary tab you will be able to see maximum heap size.
By the way, ou can increase size of java heap space based on your application need and I always recommend this to avoid using default JVM heap values. if your application is large and lots of object created you can change size of heap space by using JVM options -Xms and -Xmx. Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.
There is another parameter called -Xmn which denotes Size of new generation of Java Heap Space. Only thing is you can not change the size of Heap in Java dynamically, you can only provide Java Heap Size parameter while starting JVM
Regarding default heap size in Java, from Java 6 update 18 there are significant changes in how JVM calculates default heap size in 32 and 64 bit machine and on client and server JVM mode:
- Initial heap space and maximum heap space is larger for improved performance.
- Default maximum heap space is 1/2 of physical memory of size upto 192 bytes and 1/4th of physical memory for size upto 1Gig. So for 1Gig machine maximum heap size is 256MB 2.maximum heap size will not be used until program creates enough object to fill initial heap space which will be much lesser but at-least 8 MB or 1/64th part of Physical memory upto 1GB.
- for Server Java virtual machine default maximum heap space is 1G for 4GB of physical memory on a 32 bit JVM. for 64 bit JVM its 32G for a physical memory of 128GB. To learn more about how much memory you can set in 32-bit and 64-bit JVM in various operating system e.g. Windows 8, Linux, or Solaris, see here.
22. How to take Java Heap dump?
Java Heap dump is a snapshot of Java Heap Memory at a particular time. This is very useful to analyze or troubleshoot any memory leak in Java or any java.lang.OutOfMemoryError. There are tools available inside JDK which helps you to take heap dump and there are heap analyzer available tool which helps you to analyze java heap dump.
You can also use "jmap" command to get java heap dump, this will create heap dump file and then you can use "jhat - Java Heap Analysis Tool" to analyze those heap dumps.
23. Tell some points about java Heap?
- Java Heap Memory is part of memory allocated to JVM by Operating System.
- Whenever we create objects they are created inside Heap in Java.
- Java Heap space is divided into three regions or generation for sake of garbage collection called New Generation, Old or tenured Generation or Perm Space. Permanent generation is garbage collected during full gc in hotspot JVM.
- You can increase or change size of Java Heap space by using JVM command line option -Xms, -Xmx and -Xmn. don't forget to add word "M" or "G" after specifying size to indicate Mega or Gig. for example you can set java heap size to 258MB by executing following command java -Xmx256m HelloWord.
- You can use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java. See my post How to find memory usage in Java program for more details.
- You can use command "jmap" to take Heap dump in Java and "jhat" to analyze that heap dump.
- Java Heap space is different than Stack which is used to store call hierarchy and local variables.
- Java Garbage collector is responsible for reclaiming memory from dead object and returning to Java Heap space.
- Don’t panic when you get java.lang.OutOfMemoryError, sometimes its just matter of increasing heap size but if it’s recurrent then look for memory leak in Java.
- Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.
24. Explain some points about .class?
- class file in java is generated when you compile .java file using any Java compiler like Sun's javac which comes along JDK installation and can be found in JAVA_HOME/bin directory.
- class file contains byte codes. byte codes are special platform independent instruction for Java virtual machine. bytecode is not a machine language and mere instruction to JVM. since every machine or processor e.g. INTEL or AMD processor may have different instruction for doing same thing, its left on JVM to translate bytecode into machine instruction and by this way java achieves platform independence.
- class file of inner class contains $ in there name. So if a Java source file contains two classes, one of them is inner class than java compiler will generate two class file. separate class file for top level and inner class. you can distinguish them by looking at there name. Suppose you have top level class as "Hello" and inner class as "GoodBye" then java compiler will generate two class file:
Hello.class
Hello$GoodBye.class
Hello$GoodBye.class is a class file for inner class. whose name is in format of top-class$inner-class. - You can look bytecode of class file using javap command. javap command can also display method and field information from .class file. see my post how to decompile .class file in Java for more details.
- .class file format is subject to change and its changed to support new feature introduced in Java 1.5. In general every java compiler and JRE comes with supported version of .class file format and you can not run a .class file which is in higher version of those supported by JRE. this often result in java.lang.UnsupportedClassVersion. class file has two version major and minor which is included inside class file. See my post Bad version number in .class file for more details.
- .class file in java is identified by a magic number in header which is a 4 byte CA FE BA BE ( in hex). which is the first element in .class file, followed by major and minor versions of class file
- .class file allows Java Virtual machine to implement security. Since number of instruction class file contains are limited. also if some one tempers .class file externally it may not run on different browsers and JRE.
- Java class file can be divided into 10 basic sections e.g.
Magic Number : 0xCAFEBABE
Major and Minor class version or .class file
Constant pool - constants for this class
Access modifiers - to indicate whether class is static or abstract
This class - name of this class
Super class - name of super class
Interfaces -
Fields
Methods
Attributes - Top level .class file name is same as name of java source file e.g. Hello.java will produce Hello.class
- You can view class file in any hex editor or any byte code viewer plug-in in Eclipse.
That's all on what is class file and basics of .class file. As I said this is not a detailed article on .class file format rather this is the bare minimum information regarding .class file an average java programmer should be familiar with. I highly recommend to read more about .class file format if you are interested but it depends upon your experience level and beginners may not find the class file format easy to understand.
25. Difference Between java and javaw Commands from JDK?
ReadBoth java.exe and javaw.exe can execute java programs including jar file, only difference is that with java.exe you have a console executed and you need to wait until your java program finishes to run any other command on the other hand in case of javaw.exe no console or window is associated with execution.
you can run your java program either by using java.exe or javaw.exe. Its suggested to use javaw.exe when you don't need command line window to appear. javaw launcher will display in error in a dialog box if execution fails.
26. What is the maximum Heap Size of 32 bit or 64-bit JVM in Windows and Linux?
Maximum heap size for 32 bit or 64 bit JVM looks easy to determine by looking at addressable memory space like 2^32 (4GB) for 32 bit JVM and 2^64 for 64 bit JVM. Confusion starts here because you can not really set 4GB as maximum heap size for 32 bit JVM using -Xmx JVM heap options.
This confusion comes because of sign bit, many programmer think in terms of signed integer and they think maximum addressable memory (size of address bus) for 32 bit architecture is 2^32-1 or 2GB and this confusion is supported by fact that you can not provide maximum heap space as 2GB on windows machine. But this is wrong. Memory is nothing to do with signed or unsigned bit as there is no negative memory address. So theoretical limit for maximum heap size on 32 bit JVM is 4GB and for 64 bit JVM its 2^64.
The maximum heap size for 64 bit or x64 JVM, Is it 8GB or 16GB
This question mostly arise because of available physical memory on machine. As no system currently have 2^64 bit of physical memory or RAM and often high end servers has memory around 8G, 16GB or 32GB. Theoretical maximum memory for x64 machines is 2^64 bit but again its depend on how much your operating systems allows.I read some where that Windows allowed maximum of 32GB for 64 bit JVM.
27. Why JVM not able to start on Windows XP when maximum heap space around 1600M?
This problem is most obvious on Windows platform like Windows XP, which tries to allocate a contiguous chunk of memory as requested by -Xmx JVM parameters. Windows reserves some space for his own and seems also allocate memory around half of memory address bar, which consequently reduces contiguous memory space somewhere less than 2GB, around 1500 to 1600M and when you give more than this size, JVM throws error as.
Could not create the Java virtual machine.
Invalid initial heap size: -Xms1.5G
Remember, this limit on heap space is due to windows operating system's own behavior. You can set maximum heap space, more than this size in Linux or Solaris. Though maximum heap size for 32 bit or 64 bit JVM will always be less than theoretical limit of addressable memory. By the way you can get this error due to many reasons, see How to fix Invalid Initial and Maximum heap size in JVM for more details.
28. Types of Garbage Collector in Java?
1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the runtime via JVM command line options . The tenured generation collector is same as the serial collector.
2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is used with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses an algorithm to first mark object which needs to collect when garbage collection triggers.
3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
An important point to note is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow the legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.
29. When an Object becomes Eligible for Garbage Collection?
Generally, an object becomes eligible for garbage collection in Java on following cases:
- All references to that object explicitly set to null e.g. object = null
- The object is created inside a block and reference goes out scope once control exit that block.
- Parent object set to null if an object holds the reference to another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
- If an object has only lived weak references via WeakHashMap it will be eligible for garbage collection.
30. How to find max memory, free memory and total memory in Java?
In order to get currently free Memory available for creating object use Runtime.getRuntime().freeMemory()
method, this will return size in bytes, which you convert in Mega Bytes for better readability.
You can use Runtime.getRuntime.totalMemory()
to get total memory from JVM which represents current heap size of JVM which is a combination of used memory currently occupied by objects and free memory available for new objects.
We specify initial heap space by using -Xms and JVM creates initial heap with this much size. in order to get this size from Java program call Runtime.getRuntime.totalMemory()
before creating any object.
This is relatively easy as maximum heap space is not going to change over JVM life cycle and call to Runtime.getRuntime.maxMemory()
will return value close to -Xmx but keep in mind exact value will be little less than what have you set.
No comments:
Post a Comment