I got the following scenario: A C++ server application is listening for incomming client connections. On each client connection attempt a new session is generated. This session will call a specific service, depending on a service id, which is provided in the serialized data from the client. As soon as the result arrives from the service the session sends the data to the client.
The pitfall in the scenario is, that the service is implemented in Java.
Therefore my question is:
- How can I instantiate and call the Java service class using the VM reference from C++ if a new client request arrives?
I know I will need a Java VM for this. And because the C++ server class will be called from a Java Application in first place (through SWIG generated wrappers) I thought I might pass the VM reference of this application to my server class (and the sessions afterwards).
But:
- How can I obtain a reference to the current VM in my Java code?
Normally the Java application will be doing nothing after kicking on the server. Maybe I will have to keep it idle for keeping the VM reference alive? Is there anything special I should worry about regarding concurrent calls to the services in the C++ and Java interaction (beyond the normal concurrency handling inside the services)?
Example:
//Java Service
public class JMyService{
public String loadContactInformation(int userid){
return "test";
}
}
//C++ (very simplified)
class Session{
public:
//[...]
void handleWrite(){
vm = getVMReference(); //is saved beforehand
if(serviceId == CONTACT_INFO){
//todo call JMyService.loadContactInformation
}
}
}
I already saw this question but I have to admit that the solution is hard to understand and it remains unclear what the questioner was trying to achieve. In this post the author was doing something similar with Java build in types, but it seems that the code generator can not be used for own java types. I also knew that a new VM can be generated to do the job, but I would like to use the existing one if this is possible.
EDIT
to 1) I'm not sure, but maybe the jint JNI_OnLoad(JavaVM *vm, void *reserved);
Method can be used to obtain a pointer to the VM when I load the library with the C++ server class. Unfortunately the Oracle documentation does not explain this issue. Someone out there who might have experience with this?