1.2 Java under the hood Flashcards

(41 cards)

1
Q

What happens during Java compilation?

A

javac compiles .java source files into .class bytecode files. The process includes syntax checking, type checking, and generating platform-independent bytecode using stack-based instruction set (opcodes like iload, istore, iadd, invokevirtual).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Java bytecode and why is it important?

A

Bytecode is an intermediate representation between source code and machine code. It’s platform-independent, uses stack-based architecture, and allows “write once, run anywhere.” Bytecode gets verified for type safety and security before execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the three phases of bytecode verification?

A

1)Verification - ensures type safety and prevents buffer overflows,
2) Preparation - allocates memory for static variables,
3) Resolution - converts symbolic references to direct references.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s the relationship between JDK, JRE, and JVM?

A

JDK contains JRE + development tools (javac, javadoc, jar).
JRE contains JVM + core libraries + supporting files.
JVM is the runtime engine that executes bytecode.

Think: JDKJREJVM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What components make up the JRE?

A

JVM (execution engine), Core Libraries (java.lang, java.util, etc.), Native Method Interface (JNI), and supporting configuration files and resources needed for runtime execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain the three-tier class loading delegation model

A

1) Bootstrap ClassLoader - loads core Java classes (java.lang.), implemented in native code,
2) Extension ClassLoader - loads extension libraries from ext directory,
3) Application ClassLoader - loads application classpath classes. Child loaders delegate to parent first.*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the three phases of class loading?

A

1) Loading - finds and reads .class file into memory
2) Linking - verification, preparation, and resolution of symbolic references
3) Initialization - executes static initializers and static variable assignments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When does class initialization occur?

A

When first instance is created, static method is called, static field is accessed (except compile-time constants), class is explicitly loaded via reflection, or when initializing a subclass.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Describe the generational heap structure

A

Young Generation: Eden space (new objects) + two Survivor spaces (S0, S1).
Old Generation: Tenured space for long-lived objects.
Objects start in Eden, survive to Survivor spaces, then get promoted to Old Gen after multiple GC cycles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the generational hypothesis and why does it matter?

A

Most objects die young, so separating generations optimizes GC. Minor GC occurs frequently in Young Gen (fast), Major GC occurs less frequently in Old Gen (slower). This reduces overall GC overhead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What happens during object allocation in the heap?

A

New objects allocated in Eden space. When Eden fills, Minor GC runs. Surviving objects move to Survivor space. After several GC cycles, long-lived objects promote to Old Generation (tenured space).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Metaspace and how does it differ from PermGen?

A

Metaspace (Java 8+) stores class metadata in native memory, replacing PermGen. Unlike PermGen’s fixed size causing OutOfMemoryErrors, Metaspace grows dynamically and is limited only by available native memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain the structure of each thread’s stack

A

Each thread has its own stack containing method call frames. Each frame includes: local variable array, operand stack for intermediate calculations, and reference to the constant pool of the current class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the PC Register and Native Method Stack?

A

PC Register: stores address of currently executing instruction for each thread.
Native Method Stack: handles native method calls through JNI, separate from regular Java method stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does the HotSpot JVM’s tiered compilation work?

A

Initially, interpreter executes bytecode (quick startup). When methods become “hot” (frequently called), C1 compiler provides fast compilation with basic optimizations. For long-running hot code, C2 compiler applies aggressive optimizations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What triggers JIT compilation?

A

A: Method call counters and loop back-edge counters. When thresholds are exceeded, methods marked as “hot spots.” Profiling data collected during interpretation guides optimization decisions in compiled code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Name 5 major JIT compiler optimizations

A

1) Inlining - replaces method calls with method body,
2) Escape Analysis - stack-allocates non-escaping objects,
3) Dead Code Elimination - removes unreachable code, 4) Loop Unrolling - reduces loop overhead, 5) Vectorization - uses SIMD instructions.

18
Q

What is escape analysis and how does it optimize performance?

A

A: Determines if objects escape method scope. Non-escaping objects can be stack-allocated instead of heap-allocated, eliminating GC pressure and improving cache locality. Can also eliminate synchronization on non-escaping objects.

19
Q

How does method inlining improve performance?

A

Eliminates method call overhead, enables further optimizations on larger code blocks, improves instruction cache locality, and allows better register allocation across formerly separate methods.

20
Q

What is deoptimization in the JIT compiler?

A

When runtime assumptions used for optimization prove false, JIT “deoptimizes” - falls back to interpreter or recompiles with different assumptions. Examples: type speculation fails, class hierarchy changes.

21
Q

Explain the Mark-Sweep-Compact algorithm

A

1) Mark - traverse object graph from GC roots, marking reachable objects,
2) Sweep - deallocate unmarked (dead) objects,
3) Compact - defragment memory by moving objects together, updating references.

22
Q

What are GC roots?

A

Starting points for reachability analysis: static variables, local variables in active methods, JNI global references, objects in native method stacks, and system class loader references.

23
Q

Compare generational GC strategies

A

Minor GC - frequent, fast, Young Generation only. Major GC - less frequent, slower, Old Generation.
Full GC - entire heap + Metaspace, slowest but most thorough cleanup.

24
Q

How does G1GC differ from traditional collectors?

A

Divides heap into regions instead of generations.
Uses concurrent marking and incremental collection.
Targets specific pause time goals. Better for large heaps (>4GB) requiring low latency.

25
What makes ZGC and Shenandoah "ultra-low latency" collectors?
Concurrent collection with colored pointers/forwarding pointers. Most work happens while application runs. Pause times under 10ms regardless of heap size. Use load barriers for concurrent object relocation.
26
When would you choose different GC algorithms?
Serial GC - single-core, small applications. Parallel GC - throughput-focused, batch processing. G1GC - balanced latency/throughput, large heaps. ZGC/Shenandoah - ultra-low latency requirements.
27
Q: Describe Java object header structure
Mark Word - hashcode, GC generation info, locking information, biased locking. Class Pointer - reference to object's class metadata. Followed by instance data and padding for memory alignment.
28
What are the different reference types and their GC behavior?
**Strong** - normal references, never GC'd while reachable. **Weak** - GC'd when only weak references remain. Soft - GC'd when memory pressure exists. **Phantom** - for cleanup actions, object already unreachable.
29
How does string interning work in Java?
String literals stored in String Pool (part of heap in Java 7+). String.intern() puts string in pool, returning canonical instance. Reduces memory usage for duplicate strings, enables == comparison for interned strings
30
How does synchronized keyword work internally?
Uses monitor enter/exit bytecode instructions. Implements biased locking (single thread), thin locks (CAS-based), and thick locks (OS mutexes). Lock inflation occurs under contention.
31
What is the Java Memory Model?
Defines how threads interact through memory. Establishes happens-before relationships ensuring visibility and ordering. Volatile provides visibility guarantees. Final fields have special initialization safety guarantees.
32
Explain happens-before relationships
Program order, monitor unlock happens-before subsequent lock, volatile write happens-before volatile read, thread start/join operations. These guarantee memory visibility and prevent reordering across synchronization boundaries.
33
How does JNI (Java Native Interface) work?
Allows Java to call C/C++ code and vice versa. Creates native method stubs, manages object references across boundary, handles exceptions. Requires careful memory management and reference handling.
34
What is Project Panama's Foreign Function Interface?
Modern replacement for JNI providing more efficient native code integration. Eliminates JNI overhead through better memory layout, direct memory access, and reduced context switching
34
What are the performance implications of JNI calls?
Expensive due to context switching, parameter marshalling, GC interaction restrictions. Native code can't be optimized by JIT. Frequent JNI calls can hurt performance significantly.
35
How does dynamic class loading work?
Classes can be loaded at runtime using custom ClassLoaders. Enables plugin architectures, hot deployment, and framework magic. ClassLoaders maintain parent-delegation model and namespace isolation.
36
What is reflection and how does it impact performance?
Runtime inspection and manipulation of classes, methods, fields. Slower than direct access due to security checks, boxing/unboxing, and prevention of JIT optimizations. Use Method.setAccessible() to reduce overhead.
37
How do lambda expressions work internally?
Compiled to invokedynamic bytecode instruction. Uses MethodHandles and CallSites for efficient dispatch. Creates lightweight proxy objects implementing functional interfaces. More efficient than anonymous inner classes.
38
What JVM flags are crucial for performance tuning?
Heap sizing: -Xms, -Xmx. GC selection: -XX:+UseG1GC. JIT tuning: -XX:CompileThreshold. Monitoring: -XX:+PrintGC, -XX:+UnlockExperimentalVMOptions. Debugging: -XX:+PrintCompilation.
39
How can you monitor JVM internals?
JConsole, VisualVM for GUI monitoring. JFR (Java Flight Recorder) for low-overhead profiling. jstat for command-line GC monitoring. JProfiler/YourKit for detailed profiling. Custom JMX MBeans for application metrics.
40
What causes common JVM performance issues?
Excessive GC pauses, memory leaks, inefficient object allocation patterns, lack of JIT warmup, contention on synchronized blocks, inefficient data structures, and suboptimal GC algorithm choice for workload.