JVM related interview questions and points - tarunchhabra/parakalo GitHub Wiki
Stack memory:
- Both primitive values and references are stored in the stack memory.
--> Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.
In case of primitives, the value is simply copied inside stack memory which is then passed to the callee method; in case of non-primitives, a reference in stack memory points to the actual data which resides in the heap. When we pass an object, the reference in stack memory is copied and the new reference is passed to the method.
- Static : static variables go in a particular pool in JVM memory called Metaspace (before Java 8, this pool was called Permanent Generation or PermGen, which was completely removed and replaced with Metaspace).
The most significant difference is how it handles memory allocation.
Specifically, this native memory region grows automatically by default.
static methods in Java are resolved at compile time. Since method overriding is part of Runtime Polymorphism, so static methods can't be overridden. pp abstract methods can't be static
static methods cannot use this or super keywords
- static nested class : causes memory leak
This happens because the inner class object implicitly holds a reference to the outer class object, thereby making it an invalid candidate for garbage collection. The same happens in the case of anonymous classes.
How to Prevent It?
If the inner class doesn't need access to the containing class members, consider turning it into a static class. It won't be coupled to the outer class and hence will be more optimal as they won't require any heap or stack memory.
- Synchronized Instance Methods VS Synchronized Static Methods
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.
Static 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.