Skip to content

Instantly share code, notes, and snippets.

@eleinadani
Last active January 18, 2019 22:11
Show Gist options
  • Save eleinadani/a0637e788c8501d27bcb5b7635a09c4b to your computer and use it in GitHub Desktop.
Save eleinadani/a0637e788c8501d27bcb5b7635a09c4b to your computer and use it in GitHub Desktop.
function JavaToJSNotifier {
this.queue = new java.util.concurrent.LinkedBlockingDeque();
this.worker = new Worker(`
const { workerData, parentPort } = require('worker_threads');
while (true) {
// block the worker waiting for the next notification from Java
var data = workerData.queue.take();
// notify the main event loop that we got new data
parentPort.postMessage(data);
}`,
{eval: true, workerData: { queue: this.queue }});
}
// register a callback to be executed when something is added to the shared queue
const asyncJavaEvents = new JavaToJSNotifier();
asyncJavaEvents.worker.on('message', (n) => {
console.log(`Got new data from Java! ${n}`);
});
// pass the queue to Java, to give a way to notify us back when data is available
const MyJavaClass = Java.type('my.java.AwesomeClass');
new MyJavaClass(asyncJavaEvents.queue).start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment