Java Architecture, Memory Management Garbage Collector Cheat Sheet

Java Architecture, Memory Management Garbage Collector Cheat Sheet 

7778a2a9cd8015fa611be7cde1789cb6.png

1. Bootstrap ClassLoader6 loads classes from t6he location rt.jar

2. Extension ClassLoader loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs

3. System ClassLoader loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option.

1zI23VMfAbcW6vmsra8Hxb37f1DUSWL6NbRZAAAAAElFTkSuQmCC

java-heap-stack-diagram.png

1. Method Area is a part of the heap memory which is shared among all the threads. It is used to store class structure, superclass name, interface name, and constructors.
2. Heap stores the actual objects, When you use a new keyword While the reference of that object stores in the stack, it also stores Objects, String literals, instance variables and methods.
3. Stack Area generates when a thread creates.It contains references to heap objects.it also stores Local variables, reference variables. Stack memory is stored in computer RAM, similar to the heap.
4. PC register store the physical memory address of the statements which is currently executing. In Java, each thread has its separate PC register.
5. Java supports and uses native code as well. Many low level code is written in languages like C and C++. Native method stacks hold the instruction of native code.
6. PermGen/Metaspace Sotres class structure, static variables, static methods, static blocks


PermGen
1. (Permanent Generation) is a special heap space separated from the main memory.
2. The JVM keeps track of class metadata in the PermGen. Also, the JVM stores all the static content in this.
3. Due to limited memory size, PermGen can throw OutOfMemoryError.

Metaspace
1. It has replaced the older PermGen memory space.
2. It can now handle memory allocation.
3. Metaspace not part of heap memory ,Metaspace grows automatically by default. 

How "Garbage Collection" Works in Java?

1. Objects are created on the heap, Some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

2. There are generally 4 ways to make an object eligible for gc. It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort

     1.Nullifying reference variable, 2.Re-assigning reference variable

      3.An object created inside the method     4.Island of Isolation

3. Ways for requesting JVM to run Garbage Collector

         Using System.gc() and Using Runtime.getRuntime().gc() methods

4. Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.

5. It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory.

jdk.jpg

1. JDK The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.

2. JRE The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

3. JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn’t physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode.


Aggregation vs Composition vs Association Cheat Sheet
AggregationCompositionAssociation
Aggregation is a weak Association.Composition is a strong Association.Weakest relationship among all.
Class can exist independently without owner.Class can not meaningfully exist without owner. 
Have their own Life Time. A uses B.Life Time depends on the Owner. A owns B. 
Child is not owned by 1 owner.Child can have only 1 owner. 
Has-A relationship. A has B. Denoted by a empty diamond in UML.Part-Of relationship. B is part of A.
Denoted by a filled diamond in UML.
 
We do not use “final” keyword for Aggregation.“final” keyword is used to represent
Composition.
 
It represents the Has-A relationship.It represents a part-of-relationship. 
It is a unidirectional association i.e. a one-way relationship. For example, the department can have students but vice versa is not possible and thus unidirectional in nature.In composition, both entities are dependent on each other. 
In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.When there is a composition between two entities, the composed object cannot exist without the other entity. For example, if order HAS-A line-items, then an order is a whole, and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted. Favor Composition over Inheritance.
Relationship between two classes such that objects of both classes can have independent lifecycle, but object of one class will belong to a specific object of the another class in its lifetime. It cannot belong to two objects of the same class.It to refer to relationships where two objects don’t have an independent lifecycle, and if the parent object is deleted, all child objects will also be deleted.Association is not a has-a relationship and the weakest relationship among all. In an Association relationship, none of the objects are parts or members of another. A simple example of Association is a mother and her child.

Examples:
~ Car has a Driver.

– A Human uses Clothes.

– A Company is an aggregation of People.
~ A Text Editor uses a File.

~ Mobile has a SIM Card.

Examples:
~ Engine is a part of Car.

– A Human owns the Heart.

– A Company is a composition of Accounts.
– A Text Editor owns a Buffer.

~ IMEI Number is a part of a Mobile.

Relationships/Association 

One-to-One

One-to-Many

Many-to-One

Many-to-Many

Keyfinalfinallyfinalize
Definitionfinal is the keyword and access modifier which is used to apply restrictions on a class, method or variable.finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not.finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.
Applicable toFinal keyword is used with the classes, methods and variables.Finally block is always related to the try and catch block in exception handling.finalize() method is used with the objects.
Functionality(1) Once declared, final variable becomes constant and cannot be modified.
(2) final method cannot be overridden by sub class.
(3) final class cannot be inherited.
(1) finally block runs the important code even if exception occurs or not.
(2) finally block cleans up all the resources used in try block
finalize method performs the cleaning activities with respect to the object before its destruction.
ExecutionFinal method is executed only when we call it.Finally block is executed as soon as the try-catch block is executed. It’s execution is not dependent on the exception.

finalize method is executed just before the object is destroyed.

Using System.gc() or gc auto called

 

Making a class final means that it won’t be possible to extend that class

Adding final to a method means that it won’t be possible to override that method

Finally, putting final in front of a field, a variable or a parameter means that once the reference has been assigned then it cannot be changed (however, if the reference is to a mutable object, it’s internal state could change despite being final)

The finally block is an optional block to use with a try/catch statement. In this block, we include code to execute after the try/catch structure, whether an exception is thrown or not.And finally, the finalize method is a protected method, defined in the Object class. It’s called by the garbage collector on objects that aren’t referenced anymore and have been selected for garbage collection.



Method Overloading vs Method Overriding
Method OverloadingMethod Overriding
Method overloading is used to increase the readability of the program.Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
Method overloading is performed within class.Method overriding occurs in two classes that have IS-A (inheritance) relationship.
Both methods must have different argument lists.It must have the same arguments.
Both methods must have the same method name.It must have the same method name.
Method overloading is the example of compile time polymorphism.  Method overriding is the example of run time polymorphism.
Can’t be performed by changing return type of the method only. Return type can be same or different in method overloading. but you must have to change the parameters or order of parametersIt must have the same return type. From Java 5 onward, the return type can also be a subclass (subclasses are a covariant type to their parents).
It can have different access modifiers.It must not have a more restrictive access modifier (if parent → protected then child → private is not allowed).
It can Throw different checked or unchecked exceptions.It must not throw new or broader checked exceptions.

Apart from the above rules, there are also some facts to keep in mind:

  • Only inherited methods can be overridden. That means methods can be overridden only in child classes.
  • Constructors and private methods are not inherited, so they cannot be overridden.
  • Abstract methods must be overridden by the first concrete (non-abstract) subclass.
  • final methods cannot be overridden.
  • A subclass can use super.overridden_method() to call the superclass version of an overridden method.
exception-handling-method-overriding.png

 Singleton Method Design Pattern in Java.

1. Ensure that only one instance of the class exists.

2. Provide global access to that instance by

  • Declaring all constructors of the class to be private.
  • Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.
  • The instance is stored as a private static variable.

There are two forms of singleton design patterns, which are:

  • Early Instantiation: The object creation takes place at the load time.
  • Lazy Instantiation: The object creation is done according to the requirement.

class Singleton {
 // Static variable reference of single_instance of type Singleton
 private static Singleton single_instance = null;

 // Declaring a variable of type String
 public String s;

 // Constructor Here we will be creating private constructor restricted to this class itself
 private Singleton()
 {
  s = “Hello I am a string part of Singleton class”;
 }

 // Static method to create instance of Singleton class
 public static synchronized Singleton getInstance()
 {
  if (single_instance == null)
   single_instance = new Singleton();

  return single_instance;
 }
}

Serialization and Deserialization in Java

1. Java Serialization is a mechanism by which Java objects can be converted into a byte stream, and consequently, can be reverted back into a copy of the object. 
2. If an object to be serialized implements the Serializable interface, the process begins. Serializable is a marker interface (has no data member and method). 
3. Each serializable object is assigned a unique identifier that the JVM uses to ensure that each instance is only serialized once. If an object is referenced multiple times, subsequent references after the first serialization point to the previously serialized data, maintaining the object graph’s integrity.
4. For each object, the non-static and non-transient fields are included in the serialized representation.
5. If any field is an object that also implements Serializable, the process is recursively applied to that object.
6. The writeObject method may be implemented for custom serialization of an object.
7. Assigning SerialVersionUID: A serialVersionUID is computed if it’s not specified. This ID must match during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
8. Handling transient and static Fields: Fields declared as transient or static are ignored by the serialization process, as transient fields are not part of the persistent state of the object, and static fields are part of the class state, not the individual object state.

9. For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.

Serialization :

Student s1 =new Student(211,”ravi”);    
  //Creating stream and writing the object    
  FileOutputStream fout=new FileOutputStream(“f.txt”);    
  ObjectOutputStream out=new ObjectOutputStream(fout);    
  out.writeObject(s1);    
  out.flush();    
  //closing the stream    
  out.close();  

Deserialization  :
  ObjectInputStream in=new ObjectInputStream(new FileInputStream(“f.txt”));  
  Student s=(Student)in.readObject();  
  //printing the data of the serialized object  
  System.out.println(s.id+” “+s.name);  
  //closing the stream  
  in.close();  


String Cheat Sheet

1. What is the difference between equals() method and == operator?

The equals() method matches content of the strings whereas == operator matches object or reference of the strings.


2.Java String intern()

It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.


3. Explain String pool in Java.

String Pool, also known as SCP (String Constant Pool), is a special storage space in Java heap memory that is used to store unique string objects. Whenever a string object is created, it first checks whether the String object with the same string value is already present in the String pool or not, and if it is available, then the reference to the string object from the string pool is returned. Otherwise, the new string object is added to the string pool, and the respective reference will be returned.


4. Is String immutable or final in Java? If so, then what are the benefits of Strings being Immutable?

Yes, Strings are immutable in Java. Immutable objects mean they can’t be changed or altered once they’ve been created. However, we can only modify the reference to the string object. The String is immutable in Java because of many reasons like security, caching, synchronization and concurrency, and class loading.

5. Is String thread-safe in Java?

Strings are immutable objects, which means they can’t be changed or altered once they’ve been created. As a result, whenever we manipulate a String object, it creates a new String rather than modifying the original string object. In Java, every immutable object is thread-safe, which means String is also thread-safe. As a result, multiple threads can access a string. For instance, if a thread modifies the value of a string, instead of modifying the existing one, a new String is created, and therefore, the original string object that was shared among the threads remains unchanged.

6. Why is a string used as a HashMap key in Java?

Basically, the HashMap object can store key-value pairs. When creating a HashMap object and storing a key-value pair in that object, you will notice that while storing, the hash code of the key will be calculated, and its calculated value will be placed as the resultant hash code of the key. Now, when the key is passed to fetch its value, then the hash code of the key is calculated again, and if it’s equal to the value of the hash code initially calculated, the initial value placed as the resultant hash code of the key is retrieved or fetched.

7. How to create Immutable class in Java?

Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.

The class must be declared as final so that child classes can’t be created.

Data members in the class must be declared private so that direct access is not allowed.

Data members in the class must be declared as final so that we can’t change the value of it after object creation.

A parameterized constructor should initialize all the fields performing a deep copy so that data members can’t be modified with an object reference.

Deep Copy of objects should be performed in the getter methods to return a copy rather than returning the actual object reference)

Note: There should be no setters or in simpler terms, there should be no option to change the value of the instance variable.

8. Object Cloning in Java

The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

Student18 s1=new Student18(101,”amit”);  

Student18 s2=(Student18)s1.clone(); 

Differences between final and immutability

  • final means that you can’t change the object’s reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object’s actual value can’t be changed, but you can change its reference to another one.
  • final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables.
  • By declaring a reference variable as final, we won’t get any immutability nature, Even though reference variable is final. We can perform any type of change in the corresponding Object. But we can’t perform reassignment for that variable.
  • final ensures that the address of the object remains the same whereas the Immutable suggests that we can’t change the state of the object once created.


Abstract class vs Interface
Parameters Interface Abstract class
SpeedSlowFast
Multiple InheritancesImplement several InterfacesOnly one abstract class
StructureAbstract methodsAbstract & concrete methods
When to useFuture enhancementTo avoid independence
Inheritance/ ImplementationA Class can implement multiple interfacesThe class can inherit only one Abstract Class
Default ImplementationWhile adding new stuff to the interface, it is a nightmare to find all the implementors and implement newly defined stuff.In case of Abstract Class, you can take advantage of the default implementation.
Access ModifiersThe interface does not have access modifiers. Everything defined inside the interface is assumed public modifier.Abstract Class can have an access modifier.
When to useIt is better to use interface when various implementations share only method signature. Polymorphic hierarchy of value types.It should be used when various implementations of the same kind share a common behavior.
Data fieldsthe interface cannot contain data fields.the class can have data fields.
Multiple Inheritance DefaultA class may implement numerous interfaces.A class inherits only one abstract class.
ImplementationAn interface is abstract so that it can’t provide any code.An abstract class can give complete, default code which should be overridden.
Use of Access modifiersYou cannot use access modifiers for the method, properties, etc.You can use an abstract class which contains access modifiers.
UsageInterfaces help to define the peripheral abilities of a class.An abstract class defines the identity of a class.
Defined fieldsNo fields can be definedAn abstract class allows you to define both fields and constants
InheritanceAn interface can inherit multiple interfaces but cannot inherit a class.An abstract class can inherit a class and multiple interfaces.
Constructor or destructorsAn interface cannot declare constructors or destructors.An abstract class can declare constructors and destructors.
Limit of ExtensionsIt can extend any number of interfaces.It can extend only one class or one abstract class at a time.
Abstract keywordIn an abstract interface keyword, is optional for declaring a method as an abstract.In an abstract class, the abstract keyword is compulsory for declaring a method as an abstract.
Class typeAn interface can have only public abstract methods.An abstract class has protected and public abstract methods.


How ConcurrentHashMap Works Internally in Java

Maps are naturally one of the most widely style of Java collection.

And, importantly, HashMap is not a thread-safe implementation, while Hashtable does provide thread-safety by synchronizing operations.

Even though Hashtable is thread safe, it is not very efficient. Another fully synchronized Map, Collections.synchronizedMap, does not exhibit great efficiency either. If we want thread-safety with high throughput under high concurrency, these implementations aren’t the way to go.

To solve the problem, the Java Collections Framework introduced ConcurrentMap in Java 1.5.

The following discussions are based on Java 1.8.

ConcurrentHashMap: It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.

Concurrency-Level: Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this     many threads.

Load-Factor: It’s a threshold, used to control resizing.

Initial Capacity: The implementation performs internal sizing to accommodate these many elements.

A ConcurrentHashMap is divided into number of segments, and the example which I am explaining here used default as 32 on initialization.

A ConcurrentHashMap has internal final class called Segment so we can say that ConcurrentHashMap is internally divided in segments of size 32, so at max 32 threads can work at a time. It means each thread can work on a each segment during high concurrency and atmost 32 threads can operate at max which simply maintains 32 locks to guard each bucket of the ConcurrentHashMap.

Key points of ConcurrentHashMap:  

  • The underlined data structure for ConcurrentHashMap is Hashtable.
  • ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.
  • At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap.
  • In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.
  • The default concurrency-level of ConcurrentHashMap is 16.
  • In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads.
  • Inserting null objects is not possible in ConcurrentHashMap as a key or value.

Why use Concurrent Hashmap-

We use ConcurrentHashMap when a high level of concurrency is required. But already SynchronizedMap is present so what advantages does ConcurrentHashMap have over synchronized map.Both are thread safe. The major advantage is in case of synchronizedMap every write operation acquires lock on entire SynchronizedMap while in case of ConcurrentHashMap the lock is only on one of the segments.

java6_5                                                            java6_4