Java Architecture, Memory Management Garbage Collector Cheat Sheet
Java Architecture, Memory Management Garbage Collector Cheat Sheet |
---|
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. | |
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. PermGen Metaspace | |
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. | |
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 |
Aggregation | Composition | Association |
---|---|---|
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: – A Human uses Clothes. ~ Mobile has a SIM Card. | Examples: – A Human owns the Heart. – A Company is a composition of Accounts. ~ IMEI Number is a part of a Mobile. | Relationships/Association One-to-One One-to-Many Many-to-One Many-to-Many |
Key | final | finally | finalize |
---|---|---|---|
Definition | final 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 to | Final 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. |
Execution | Final 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 Overloading | Method 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 parameters | It 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:
|
Singleton Method Design Pattern in Java.
1. Ensure that only one instance of the class exists. 2. Provide global access to that instance by
There are two forms of singleton design patterns, which are:
| class Singleton { // Declaring a variable of type String // Constructor Here we will be creating private constructor restricted to this class itself // Static method to create instance of Singleton class 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. 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”); Deserialization : |
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.
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.
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.
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
|
Abstract class vs Interface | ||
---|---|---|
Parameters | Interface | Abstract class |
Speed | Slow | Fast |
Multiple Inheritances | Implement several Interfaces | Only one abstract class |
Structure | Abstract methods | Abstract & concrete methods |
When to use | Future enhancement | To avoid independence |
Inheritance/ Implementation | A Class can implement multiple interfaces | The class can inherit only one Abstract Class |
Default Implementation | While 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 Modifiers | The interface does not have access modifiers. Everything defined inside the interface is assumed public modifier. | Abstract Class can have an access modifier. |
When to use | It 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 fields | the interface cannot contain data fields. | the class can have data fields. |
Multiple Inheritance Default | A class may implement numerous interfaces. | A class inherits only one abstract class. |
Implementation | An 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 modifiers | You cannot use access modifiers for the method, properties, etc. | You can use an abstract class which contains access modifiers. |
Usage | Interfaces help to define the peripheral abilities of a class. | An abstract class defines the identity of a class. |
Defined fields | No fields can be defined | An abstract class allows you to define both fields and constants |
Inheritance | An interface can inherit multiple interfaces but cannot inherit a class. | An abstract class can inherit a class and multiple interfaces. |
Constructor or destructors | An interface cannot declare constructors or destructors. | An abstract class can declare constructors and destructors. |
Limit of Extensions | It can extend any number of interfaces. | It can extend only one class or one abstract class at a time. |
Abstract keyword | In 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 type | An interface can have only public abstract methods. | An abstract class has protected and public abstract methods. |
How ConcurrentHashMap Works Internally in JavaMaps 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:
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. |