Reputation: 5977
I'd like to preload entire jar file with all classes and resources at the start time. So that no access to the HDD was required for further java program execution.
What is the recommended way for doing so?
update:
The jar is mastered with proguard, it detects some kind of dead code and removes it from the output. So loading classes that would never be used is not a problem.
Upvotes: 3
Views: 1909
Reputation: 719238
The recommended way is to not do this. It is going to create too many problems.
The problem is that (in general) you cannot guarantee have loaded all of the classes that need to be loaded ... unless you do a detailed analysis of your code and the library code (including Java SE libraries) that it depends on. And that analysis is hard due to that fact that some components may do dynamic class loading.
In theory, you could traverse the classloader tree's namespace and load every class. But you would end up loading vast amounts of code that isn't ever going to be used by your application.
Thinking outside the box ...
You could read the JAR file into memory, and the use a custom classloader to load from the in-memory copy. However, there is a problem with that. The standard JarFile
and ZipFile
APIs doing allow you to read from a stream or an in-memory buffer. So you would need to use JarInputStream
to iterate the JAR's entries, read the corresponding content, and cache them in memory.
Of course, if loading an application class triggers loading a class from the standard libraries, then your application needs to read from disc. (Unless you cache the core library JAR and ZIP files.)
Then there is the thorny problem that some classes depend on dynamically loaded native libraries, and that dependency is not resolved at class load time. Those native libraries will be on disk too.
And there may be other resources in your application JAR file (images, prorty files, etc) that may be read dynamically by the application.
Upvotes: 2
Reputation: 23562
You can take a look at Reflections library.
However, you should think about permgen size and memory utilization, it may happen that you just make things worse regarding HDD usage.
Also, keep in mind JRE/JDK classes, they are not present in the jar to which an app's classes are compiled and packaged.
Upvotes: -1