how JIT deals with hotcode??

Before we begin we are dealing with these questions::
if some same piece of code is running lets say 100000 times and JIT is converting from bytecode to machine code , isn’t it inefficient doing the same thing again?
if there is some piece of code which is repeating as we said , how to identify it?
🧠 What Is JIT Compilation?
The JVM uses a JIT compiler to convert frequently used bytecode into native machine code while your program is running. This means that Java doesn’t always interpret bytecode one instruction at a time — it optimizes parts of the code dynamically to run much faster.
This process is called Just-In-Time (JIT) compilation because it happens while the program is executing, not before.
🔥 What Is “Hot Code”? Hot code is just a fancy way of saying: code that runs a lot.
Examples:
A method that’s called thousands of times
A loop that runs millions of iterations
The JVM watches which parts of your program are executed frequently. Once a threshold is reached — for example, a method is called 10,000 times — it flags that code as hot, and hands it off to the JIT compiler.
⚙️ When Does the JVM Actually Compile Hot Code? Does the JVM compile hot code before running the program or during it?
Answer is JIT compilation happens while the program is already running.
Let’s say you have this simple Java loop:
for (int i = 0; i < 100_000; i++) { System.out.println(i); } Here’s what happens:
When the loop starts, System.out.println(i) is interpreted, not compiled.
The JVM keeps track of how many times the loop (and that method) executes.
After about 10,000 iterations, the JVM marks the code as hot.
The JIT compiler kicks in right then and compiles that code into native machine code.
The rest of the loop (from ~10,001 to 100,000) runs using compiled machine code, which is significantly faster.
So, the JVM switches from interpreting to compiled execution mid-loop —> while you’re still printing numbers.
Subscribe to my newsletter
Read articles from Kartikey choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
