Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call java code from Go without invoking the JVM for every call?

Tags:

java

go

Is it possible (and if so, what is the recommended way) to call java code from Go, without the need to start the JVM for every function call?

I.e, is there any equivalent to the jpype solution for python, which lets you start the JVM once, and then import java classes and call them, using the already started up JVM?

like image 628
Samuel Lampa Avatar asked Dec 09 '13 17:12

Samuel Lampa


People also ask

Will Java code be executed without JVM?

You can't run Java program without JVM. JVM is responsible in running a Java program, but the only file that can be executed by JVM is Java bytecode, a compiled Java source code.

Can you call Java from go?

You can make a Java management class in Java which is capable of talking to your Go program, and which you run once and will make the appropriate calls to other Java code when your Go program asks for them.

Is Go interoperable with Java?

By compiling their Go packages into C-style shared libraries, Go programmers can easily make their projects work with C, Python, Ruby, Node, Java, etc. using in-process integration of shared object binaries.


2 Answers

Use cgo to call into C code that creates a JVM instance using the JNI invocation API, and call into Java code using the JNI interface. As goroutines can technically switch between native threads, you'll probably have to be very careful about testing, attaching and detaching threads to the JVM upon entry and exit from Go code and/or supplement with use of a native threads library like pthreads.

like image 131
Jman Avatar answered Nov 15 '22 15:11

Jman


Bundle your java code in a "server" and call it with RPC like "rest/soap/thrift" and keep the server running. I don't know of any system that automate this for you though.

like image 33
skyde Avatar answered Nov 15 '22 15:11

skyde