I have a Java application on a USB stick along with the JRE (one for each Windows, Mac OSX and Linux) so that it can be run on any system even when Java is not installed. I have a thread running to detect if the USB stick is removed and if it is it exits the application.
I want to have it display a message before exiting (or tell them to re-insert the drive) but if I try to dispaly a JOptionPane I get the NoClassDefFoundError because the JRE has been removed along with the USB.
Is there a way to keep the needed classes in memory so that Java does not try to load them from the filesystem that is no longer present?
Thanks!
For most runtimes, any classes that are loaded will be in RAM, in the PermGen section of Java’s memory.
To my mind what’s likely happening is that displaying the error requires classes that haven’t been loaded before – which are only available on the drive that’s no longer there.
You might be able to work around this by triggering your error displaying logic when the program starts up, except have it in a mode where it’s displayed invisibly. This should exercise the same code path such that all the required classes are loaded, and ensure that they’re already known when you need to display your error. If this is too difficult, you could just manually call
Class.forName("javax.swing.JOptionPane")instead (for each class required), though this is more brittle and likely to break if you change your rendering code without updating the hard-coded classes to load.If this isn’t the case (i.e. all the required classes have previously been loaded, and you still have the problem) then your runtime is obviously unloading classes. You’d have to look at its documentation to see what it’s doing here, and how to stop it.