I
I
Igor2016-02-22 19:02:05
Java
Igor, 2016-02-22 19:02:05

How to "warm up" a method in Java?

Hello, I ran into this problem:
I noticed that in Java, methods need extra time to "load" on the first / second use.
Therefore, the execution time of the first, and sometimes the second method call in the loop is 2.5-1.5 times longer than the subsequent ones.
Example: Method 1 and Method 2 execution time (milliseconds) in a loop:
Method 1: 481, 275, 287, 252, 256, 246, 242, 268, 235, 236, 250, 258, 259, 245, 253, 240
Method 2: 334, 102, 70, 80, 90, 80, 90, 70, 90, 80, 80, 72, 80, 70, 81, 70
Both methods send an HTTP request, but each to a different server.
Question: Is there a way to make the first calls as fast as the next ones?
PS I have these methods called in a separate thread, when there is a need, not regularly, and each time they are executed as for the first time.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2016-02-22
@ApolonIn

The JIT compiler needs to execute the code in order to figure out how to compile it.

S
Saboteur, 2016-02-22
@saboteur_kiev

Look at the java machine startup options. There are options for delayed compilation and forced compilation.
But in the case of pre-run compilation and run-time compilation, the result will be different, because some metrics will be collected at run time, which can help to compile more optimized code.

P
poiuy7, 2016-02-26
@poiuy7

1) Maybe you have lazy initializations
2) See about "java -server" vs "java -client"

V
void_phoenix, 2016-03-04
@void_phoenix

Java uses the jd method call count to understand how often it is used and whether it needs to be compiled.
Regulated by the
-XX:CompileThreshold=N flag.
The default value for N is 1500 for the client VM (32 bit systems and most likely for tiered compilation, which is what you are probably using).
You also need to take into account that most likely it is your method that will not compile. Really commonly used methods like toString, equals, etc. will compile.
The question is, do you really have methods that are called 1500 times in 2 requests?
Maybe you are just using a library for HTTP requests that caches some context on the first calls? Typically, in network applications, the request time is much longer than the code itself, so I would dig in this direction.
UPD: In general, if the project is not commercial, take java mission control and look at what your time is really spent there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question