Java loads the resources as they are needed. This make my tiny small desktop application to be very slow when opening a window.
How can I do to load all the resources when starting the app? Is something related to classloaders?
EDIT: does this code work if the files are inside a jar?
EDIT2: Note that the aim is not to reduce the startup time, but to reduce the time of new windows opening after the app is started. I want all resources to go to the memory and stay "ready for use", so after loaded the app will run faster the user's commands.
Java loads the resources as they are needed.
Actually, it is more complicated than that. If you have a class A that statically depends on a class B that statically depends on a class C, then loading A will trigger eager loading of B and C and so on. But some libraries (and I think AWT and Swing do this) internally use the Class.forName(...) method to lazily load implementation classes. This reduces the number of classes that are loaded initially, and (ideally) avoids loading code that your application will never use.
How can I do to load all the resources when starting the app?
I suppose that you could create explicit static dependencies to defeat the laziness above, but that probably won't make your application's initial window appear more quickly. A better strategy would be to try to use more lazy loading to reduce the amount of code that needs to be loaded to get the initial window visible. But this needs to be done judiciously. If you lazyily load classes that are needed for the initial window, you may actually make startup slower.
Compiling to native code (using GCJ for example) is another alternative, but this has various downsides; e.g. larger binaries, more native library dependencies, portability issues, (possibly) slower execution speed for a long running application.
Re your EDIT: I think that code will "work", but I don't see how it could possibly speed up your application's startup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With