Core Java,Collections,MultiThreading,JSP/Servlets,Angular,CI/CD with Bamboo & Jenkins,
Docker,AWS,Design Patterns,FullStack developer,Spring mvc,
==============================================================================================================
Pre requisites for singleton class
Why we declare variable or method static in Singleton class
What if there is only one line in a synchronized method. What is preferred - synchronized method or block ?
============================================================================================================================
PermGen vs MetaSpace
PermGen is an abbreviation for Permanent Generation and it’s a special heap space which is separate from the main Java heap where JVM keeps track of metadata (contains data about bytecode, names and JIT information) of the classes which have been loaded. In Java 8, PermGen has been renamed to Metaspace - with some subtle differences. From our perspective, it is important to note that Metaspace has an unlimited default maximum size. On the contrary, PermGen from Java 7 and earlier has a default maximum size of 64 MB on 32-bit JVM and 82 MB on the 64-bit version.
It is worthwhile to mention that prior to Java 7, interned Strings used to be kept on the PermGen. That caused some serious problems with the infamous:
java.lang.OutOfMemoryError: PermGen space
Whenever there is a need to resize PermGen/Metaspace, JVM will do it as it does with the standard heap. Resizing those spaces requires a full GC, which is always an expensive operation. It can usually be observed during a startup when a lot of classes are being loaded. Especially if the application has dependencies on many external libraries. If there are a lot of full GCs during the startup, it’s usually because of that. If that case, increasing the initial size can boost the startup performance.
To increase PermGen, we have the following commands:
-XX:PermSize=N - sets the initial (and minimum size) of the Permanent Generation space.
-XX:MaxPermSize=N - sets the maximum size of the Permanent Generation space.
In Java 8 and onwards, we can set the initial and maximum size of Metaspace using the following commands:
-XX:MetaspaceSize=N - sets the initial (and minimum size) of the Metaspace.
-XX:MaxMetaspaceSize=N - sets the maximum size of the Metaspace.
Courtesy: https://dzone.com/articles/permgen-and-metaspace
Explanation 2:
Metaspace by default auto increases its size (up to what the underlying OS provides), while PermGen always has a fixed maximum size. You can set a fixed maximum for Metaspace with JVM parameters, but you cannot make PermGen auto increase.
To a large degree it is just a change of name. Back when PermGen was introduced, there was no Java EE or dynamic class(un)loading, so once a class was loaded it was stuck in memory until the JVM shut down - thus Permanent Generation. Nowadays classes may be loaded and unloaded during the lifespan of the JVM, so Metaspace makes more sense for the area where the metadata is kept.
Courtesy:
https://stackoverflow.com/questions/27131165/what-is-the-difference-between-permgen-and-metaspace
Explanation 3:
In JDK7, the effort to remove the
permanent generation was started and some parts of the data residing in the
permanent generation were moved to either the Java Heap or to the native heap.
Permanent generation was not completely removed and it still exists in JDK 7
and its updates. Here's the list of things that were moved out of the permanent
generation in JDK7:
Symbols were moved to the native heap
Interned strings were moved to the Java Heap
Class statics were moved to the Java Heap
Permanent generation has been completely removed in JDK 8.
In JDK 8, classes metadata is now stored in the native heap and this space is called Metaspace.
By default class metadata allocation is only limited by the amount of available native memory. We
can use the new option MaxMetaspaceSize to limit the amount of native memory
used for the class metadata. It is analogous to MaxPermSize. A garbage collection is induced to collect the dead classloaders
and classes when the class metadata usage reaches MetaspaceSize (12Mbytes on
the 32bit client VM and 16Mbytes on the 32bit server VM with larger sizes on
the 64bit VMs). Set MetaspaceSize to a higher value to delay the induced
garbage collections. After an induced garbage collection, the class metadata usage
needed to induce the next garbage collection may be increased.
Courtesy: https://blogs.oracle.com/poonam/about-g1-garbage-collector,-permanent-generation-and-metaspace
Q&A:
Is MetaSpace by default is GC collected?
Yes, GC will run on metaspace when its getting full, it would also dynamically increase (given its allowed to) the memory allocated for metadata.
Even the PermGen is GC collected by adding the args like -XX:+CMSClassUnloadingEnabled, then what makes MetaSpace better than PermGen?
The improvement is with the dynamic expansion of the metaspace which is something permgen wasn't able to do.
MetaSpace is based on native memory, so it keeps the java objects on the disks rather than on VM?
Based on the description of metaspace, it only uses the native memory (no paging). Disk is not native memory but storage device. Native memory, in this context is the area, is the memory for the process left over from the Java heap
Based on the research by Pierre - Hugues Charbonneau (link here) its clear that the introduction of metaspace doesn't necessarily solve the OOM issue, its a bandaid to the problem at best, it attempts to dynamically resize the metaspace memory to accomodate the growing number of classes which get loaded with a possible side effect of growing uncontrollably (so long as the native memory permits it)
Even MetaSpace can run out of memory?
Yes, it is limited by the amount of memory in your machine.
Courtesy:https://stackoverflow.com/questions/24074164/what-is-the-use-of-metaspace-in-java-8
Explanation 4:
The permanent Generation is part of your heap space that is actually used to store meta-data information for the classes created by users and prior to Java 7, it is also used to store interned Strings (interned strings – used to remove String duplicates by internalizing them to reduce memory consumption). As of Java 7, intern strings also moved as a part of heap space to make the more space available in Permanent Generation.
As a Java developer I am sure that all of us have seen this very famous OutOfMemoryError: PermGen Space error and it happens when Permanent Generation space is full , which is mostly happened by memory leak. Most common reason for a memory leak is when loaded classes and class loaders are not garbage collected when they are undeployed.
Metaspace in Java8:
PermGen has been completely replaced by MetaSpace in Java8, a native memory to store class meta-data information and that grows automatically. Good thing is that as of Java 8, we will never see OutOfMemoryError : PermGen Space error , moreover we won’t have to tune PermSize and MaxPermSize arguments at the start-up of application. On the contrary these two jvm arguments are now replaced by MetaspaceSize and MaxMetaspaceSize. These two new flags gives us the flexibility to change the value for default size of metaspace and to change the maximum value that this metaspace can take.
Courtesy: http://techidiocy.com/metaspace-java8/
The key difference between PermGen and Metaspace is this: while PermGen is part of Java Heap (Maximum size configured by -Xmx option), Metaspace is NOT part of Heap. Rather Metaspace is part of Native Memory (process memory) which is only limited by the Host Operating System.
Courtesy: http://karunsubramanian.com/websphere/one-important-change-in-memory-management-in-java-8/
INSERT IMG: http://karunsubramanian.com/wp-content/uploads/2014/07/Java8-heap.jpg
==============================================================================================================
Static keyword in java
static is a non-access modifier in Java which is applicable for the following:
blocks
variables
methods
nested classes
When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object
// Java program to demonstrate use of static blocks
class Test
{
// static variable
static int a = 10;
static int b;
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static variables:
When a variable is declared as static, then a single copy of variable is created and shared among all objects at class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Important points for static variables :-
We can create static variables at class-level only. See here
static block and static variables are executed in order they are present in a program.
Below is the java program to demonstrate that static block and static variables are executed in order they are present in a program.
class Test
{
// static variable
static int a = m1();
// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
// static method(main !!)
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}
Output:
from m1
Inside static block
Value of a : 20
from main
Static methods:
When a method is declared with static keyword, it is known as static method. The most common example of a static method is main( ) method.As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object.Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
When to use static variables and methods:
Use the static variable for the property that is common to all objects. For example, in class Student, all students shares the same college name. Use static methods for changing static variables.
Example:
// Student class
class Student
{
String name;
int rollNo;
// static variable
static String cllgName;
// static counter to set unique roll no
static int counter = 0;
public Student(String name)
{
this.name = name;
this.rollNo = setRollNo();
}
// getting unique rollNo
// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}
// static method
static void setCllg(String name){
cllgName = name ;
}
// instance method
void getStudentInfo(){
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);
// accessing static variable
System.out.println("cllgName : " + cllgName);
}
}
//Driver class
public class StaticDemo
{
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
s1.getStudentInfo();
s2.getStudentInfo();
}
}
Output:
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ
<INSERT IMAGE>
Static nested classes : We can not declare top-level class with a static modifier, but can declare nested classes as static. Such type of classes are called Nested static classes.
static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).
Ref: https://www.geeksforgeeks.org/static-keyword-java/
static members belong to the class instead of a specific instance.
It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances. - Ref: https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class
----------------------------------------------------------------------------------------------------------
Synchronized in Java:
The synchronized Keyword
The synchronized keyword can be used on different levels:
Instance methods
Static methods
Code blocks
When we use a synchronized block, internally Java uses a monitor also known as monitor lock or intrinsic lock, to provide synchronization. These monitors are bound to an object, thus all synchronized blocks of the same object can have only one thread executing them at the same time.
Synchronized Instance Methods
Simply add the synchronized keyword in the method declaration to make the method synchronized:
public synchronized void synchronisedCalculate() {
setSum(getSum() + 1);
}
Instance methods are synchronized over the instance of the class owning the method. Which means only one thread per instance of the class can execute this method.
Synchronized Static Methods
Static methods are synchronized just like instance methods:
public static synchronized void syncStaticCalculate() {
staticSum = staticSum + 1;
}
These methods are synchronized on the Class object associated with the class and since only one Class object exists per JVM per class, only one thread can execute inside a static synchronized method per class, irrespective of the number of instances it has.
Synchronized Blocks within Methods
Sometimes we do not want to synchronize the entire method but only some instructions within it. This can be achieved by applying synchronized to a block:
public void performSynchrinisedTask() {
synchronized (this) {
setCount(getCount()+1);
}
}
Notice, that we passed a parameter this to the synchronized block. This is the monitor object, the code inside the block get synchronized on the monitor object. Simply put, only one thread per monitor object can execute inside that block of code.
In case the method is static, we would pass class name in place of the object reference. And the class would be a monitor for synchronization of the block:
public static void performStaticSyncTask(){
synchronized (SynchronisedBlocks.class) {
setStaticCount(getStaticCount() + 1);
}
}
Ref: https://www.baeldung.com/java-synchronized
Explanation 2:
Object level lock vs class level lock – Important notes
Synchronization in Java guarantees that no two threads can execute a synchronized method, which requires same lock, simultaneously or concurrently.
synchronized keyword can be used only with methods and code blocks. These methods or blocks can be static or non-static both.
When ever a thread enters into Java synchronized method or block it acquires a lock and whenever it leaves synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
Java synchronized keyword is re-entrant in nature it means if a synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
Java synchronization will throw NullPointerException if object used in synchronized block is null. For example, in above code sample if lock is initialized as null, the “synchronized (lock)” will throw NullPointerException.
Synchronized methods in Java put a performance cost on your application. So use synchronization when it is absolutely required. Also, consider using synchronized code blocks for synchronizing only critical section of your code.
It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
According to the Java language specification you can not use synchronized keyword with constructor. It is illegal and result in compilation error.
Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all.
Do not use String literals because they might be referenced else where in the application and can cause deadlock. String objects created with new keyword can be used safely. But as a best practice, create a new private scoped Object instance OR lock on the shared variable itself which we want to protect
Ref: https://howtodoinjava.com/java/multi-threading/object-vs-class-level-locking/
----------------------------------------------------------------------------------------------------------
Java 9 features:
Declaring HashMap inline: Map<Integer,String> map = Map.of(1, "A", 2, "B", 3, "C");
<INSERT_IMAGE> - https://javatutorial.net/wp-content/uploads/2017/09/java-initialize-hashmap.png
Ref: https://javatutorial.net/java-hashmap-inline-initialization
-----------------------------------------------------------------------------------------------------------
Core Java,Collections,MultiThreading,JSP/Servlets,Angular,CI/CD with Bamboo & Jenkins,
Docker,AWS,Design Patterns,FullStack developer,Spring mvc,
==============================================================================================================
Pre requisites for singleton class
Why we declare variable or method static in Singleton class
What if there is only one line in a synchronized method. What is preferred - synchronized method or block ?
============================================================================================================================
How can I write a new Immutable class.
Ans:
Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like String, Boolean, Byte, Short) and String class is immutable.
Another example from JDK is the wrapper classes like: Integer, Float, Boolean … these classes don’t modify their state, however they create a new instance each time you try to modify them.
Integer a =3;
a += 3;
After calling a += 3, a new instance is created holding the value: 6 and the first instance is lost.
To create immutable class in java, you have to do following steps.
Make your class final, so that no other classes can extend it.
1.Make your class final, so that no other classes can extend it.
2.Make all your fields final, so that they’re initialized only once inside the constructor and never modified afterward.
3.Don’t expose setter methods.
4.When exposing methods which modify the state of the class, you must always return a new instance of the class.
5.If the class holds a mutable object:
Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through constructor, this is to prevent the clients who pass the object from modifying it afterwards.
Make sure to always return a clone copy of the field and never return the real object instance.
Ref: https://dzone.com/articles/how-to-create-an-immutable-class-in-java
No comments:
Post a Comment