Reputation: 59
I have a JVM which is already running. I have its processID with me. Now I wish to run some other Java code inside this JVM,i.e., the code should run in this existing JVM rather than spinning up its own JVM.
I have already looked at the Attach API. However it requires code to be packaged in a JAR.
Is there any other way?
Upvotes: 5
Views: 2723
Reputation: 21004
The easiest way seems to be with the Attach API. However since you don't want to use it, you might want to google about RMI/JMS/JMX which would also allow you to do similard manipulation.
If you start the program using the standard java
command, then a new VM will be created for each program.
However, since this look like an XY problems, here an easier alternative that would probably allow you to do what you want.
It is possible to run programs on different threads of the VM.
Here an interesting snippet that would create a simple launcher, then you can start the program giving the main class of each program you want to start as argument to the main method which will create a new thread for each program, but everything will be running on the same VM as the launcher.
public class Launcher {
public static void main(String[] args) throws Exception {
for (int i = 0; i<args.length; i++) {
final Class clazz = Class.forName(args[i]);
new Thread(new Runnable() {
@Override
public void run() {
try{
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{});
} catch(Exception e) {
// improper exception handling - just to keep it simple
}
}
}).start();
}
}
}
Note : I don't know what you are really trying to do, but if it is to be used with big applications, you might want to increase the heap properties to avoid problems.
Upvotes: 1