I am investigating ways to implement some hot-reloading of Java classes. The technique I am thinking about is something like this:
- keep all classes from foreign/core libraries in memory
- if one of my files changes, remove all my classes from memory and reload all my classes. I won't have to reload any libraries in memory, because they won't change and don't depend on my files/classes.
public class Server implements Runnable {
private Thread current;
public void run(){
// create a new classloader and load all my classes from disk?
}
public Server start(){
if(this.current != null){
this.current.destroy(); // not sure if this works
}
this.current = new Thread(r);
this.current.start();
return this;
}
public static void main(String[] args){
var s = new Server().start();
onFileChanges(filePath -> {
// we don't really care what file changed
// as long as it's one of our project's files, we reload all classes
s.start();
});
}
}
I think the key idea is that I can just reload all the classes from my project, instead of trying to calculate some dependency tree.
My main questions are -
(a) how do I stop/kill a thread? Thread#destroy is deprecated.
(b) how can I remove all classes from the classloader in memory?
(c) how can I keep all the classes for libraries in memory, but remove all references to classes/instances of my code from memory?
Does anyone think this technique will work? Is an implementation possible?