简体   繁体   中英

Java reflection performance drops when packaged as jar

I have a real head-scratcher here. I tried everything, searched everywhere. It comes from an application I inherited that test JARs.

(It consists of a GUI front and a command-line application that does the actual checking. The GUI runs the command-line app by launching a new JVM on itself [java -cp "itself.jar" com.different.mainClass]. It's a bad design, I know, but may be relevant.)

Anyway, this program contains some reflection calls nested inside two for-loops. The problem is that when the application is JARed up, the first reflection call takes exactly one second every iteration. But when it runs from classes, it takes a few milliseconds.

Practically, this means this command:

java -jar myjar.jar

takes hours.

This command:

java -cp "...[bunch of jars];myjar.jar" com.myclasses.main

takes minutes.

The JAR being tested is always a jar. The difference is only in the test application.

Any ideas or avenues to pursue are greatly appreciated. Thank you!

You could consider running your program under a profiler like the Eclipse TPTP or YourKit and more precisely identify where your time is being spent. That will very likely point you to an error in your code, or somewhat less likely to point to a bug in a library. Then, if you cannot figure it out still, post the relevant code here and we can help out.

I don't know if this is related to your problem or not, but the "-cp" arguments in this command will be ignored:

$ java -cp "...[bunch of jars]" -jar myjar.jar

The "-cp" and "-jar" command options cannot be used together. An executable JAR file gets its classpath from the JAR manifest.

I don't see how this explains the symptoms you are seeing ... but it does mean that what you are trying to do with an executable JAR won't work, and that maybe renders your question moot.


FOLLOWUP

Given that that was just a bug in the question ... not the real problem ...

My suggestion is that you run your tests using the 2nd form of java command; ie with the -cp option and a classpath. It is hard to see how it would make any difference to the effectiveness of your testing regime.

I suspect that identifying the root cause of the performance problem would entail a detailed examination of what the tester application is doing.

As mentioned by others, you really need to profile the code to see where it is spending its time.

If I had to guess, I would suspect that the reflections work is resulting in repeated look ups to a class loader and loading a class is slower when extracting it from a jar file.

But again, that is just a hunch. You need to profile it to be sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM