Posts

Showing posts with the label Java

Classloader in Java

Image
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. ClassLoader main responsibilities are as below. 1) Loading 2) Linking 3) Initialization Loading :  The Class loader reads the .class file, generate the corresponding binary data and save it in method area. For each .class file, JVM stores following information in method area. Fully qualified name of the loaded class and its immediate parent class.Whether .class file is related to Class or Interface or Enum Modifier, Variables and Method information etc. After loading .class file, JVM creates an object of type Class to represent this file in the heap memory. Plea...

How JVM Works – JVM Architecture?

Image
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications.JVM is a part of JRE(Java Run Environment).Java applications are called WORA (Write Once Run Everywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java enabled system without any adjustment. This is all possible because of JVM. What exactly is JVM ? A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies. An implementation Its implementation is known as JRE (Java Runtime Environment). Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. Following is the structure of java code execution .    Initially the java source code is compiled by compiler and converted into .class file which contains bytecode. After that ....

PermGen Vs MetaSpace

PermGen Prior to Java 8 there existed a special space called the ‘Permanent Generation’. This is where the metadata such as classes would go. Also, some additional things like internalized strings were kept in Permgen. Note that Perm Gen is not part of Java Heap memory.Perm Gen is populated by JVM at runtime based on the classes used by the application. Perm Gen also contains Java SE library classes and methods. Perm Gen objects are garbage collected in a full garbage collection. It actually used to create a lot of trouble to Java developers, since it is quite hard to predict how much space all of that would require. Result of these failed predictions took the form of java.lang.OutOfMemoryError: Permgen space . Unless the cause of such OutOfMemoryError was an actual memory leak, the way to fix this problem was to simply increase the permgen size similar to the following example setting the maximum allowed permgen size to 256 MB:  java -XX:MaxPermSize=256m com.mycompany.MyAppl...

Garbage Collection Internal Working

Image
In Java Garbage Collector was created based on the following two hypotheses. (It is more correct to call them suppositions or preconditions, rather than hypotheses.)  Most objects soon become unreachable. References from old objects to young objects only exist in small numbers. These observations come together in the Weak Generational Hypothesis. Based on this hypothesis, the memory inside the VM is divided into what is called the Young Generation and the Old Generation. The latter is sometimes also called Tenured. Since the GC algorithms are optimized for objects which either ‘die young’ or ‘are likely to live forever’, the JVM behaves rather poorly with objects with ‘medium’ life expectancy. Memory Pools The following division of memory pools within the heap should be familiar. What is not so commonly understood is how Garbage Collection performs its duties within the different memory pools. Notice that in different GC algorithms some implementation details mi...

Garbage Collection

In Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects.Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.Garbage collector is best example of Daemon thread as it is always running in background. Advantage of Garbage Collection It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory. It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts. As we have seen that the Garbage collector destroy the object which have no reference in the memory. So now we will the different ways to Unreferenced the object. There are many ways: By nulling the reference By assigning a reference to another By annonymous object etc. Isolation Island 1) By nulling a reference: Integer i = new Integer(4); // the new Integer object is reachable via the reference ...

Different ways of getting a new object in Java

There are different ways of creating a new object in java . Few of them are explained as below : 1) new operator 2) reflection 3) deserialization 4) cloning Using new operator : It is the most common and regular way to create an object and a very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parameterized). MyClass mc = new MyClass(); Using Reflection:  We can also use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor to create the object. using Class.forName(“<fully-qualified-class-name> ”) Class c = Class.forName("com.codingfewer.MyClass"); c.newInstance(); Here code will compile without any issues, ie, with/without presence of MyClass.java in the classpath. But at runtime if the class is not found then it will throw run time exception. For this reason we are forced to handle ClassNotFoundException, it is a...

Hashmap internal working

Image
Hashmap works on the principle of Hashing. Hashing works on the three terms : Hash Function, Hash value and Bucket. Now we will go through each of them one by one. Hash Function  : Hash Function in hashing is the function which converts an Object into integer form. In Java hashcode() method does this work. Hash Value : Hash Value in java is the integer value returned by the Hash Function by converting memory address into Integer to find the index in bucket. Bucket : Bucket is used to store key value pairs.  Bucket can store multiple key value pair. In hashmap bucket use linked list to store objects. As we have understand the Hash Function , Hash Value and Bucket concepts in Hashing. Now we will see what is hashCode() method in Java API and How does it gives integer value of memory address. hashCode() hashCode() method is used to get the hash Code of an object. hashCode() method of object class returns the memory reference of object in integer form. Definition of...

Immutable Class

Immutable objects are instances whose state doesn’t change after it has been initialized. For example, String is an immutable class and once instantiated its value never changes.Everytime we try to append() or concatenate() something with String it creates a new String but it does not change the same String. Benefits of Immutable Class 1) Immutable class is good for caching purpose because you don’t need to worry about the value changes. 2) Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to worry about thread safety in case of multi-threaded environment. How to make immutable class Declare the class as final so it can’t be extended. Make all fields private so that direct access is not allowed. Don’t provide setter methods for variables Make all mutable fields final so that it’s value can be assigned only once. Initialize all the fields via a constructor performing deep copy. Perform cloning of objects in the getter methods to ret...

Deep Cloning and Shallow Cloning

Image
What is Cloning  ? Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process. Both shallow copy and deep copy are related to this cloning process. The default version of clone() method creates the shallow copy of an object. To create the deep copy of an object, you have to override the clone() method . Let’s see how these shallow copy and deep copy work. Shallow Cloning The default version of clone() method creates the shallow copy of an object. The shallow copy of an object will ha...