But what if you want to implement something like WebWorkers? You would likely create a new V8Runtime and execute a script on a separate thread — but this will fail! Starting with J2V8 3.0 you can now interact with J2V8 from different threads, with one rule: All interactions with a V8Runtime must be from the thread that instantiates the Runtime. This means that you can create a V8Runtime for each thread in the system, and each thread can interact with its own V8Runtime independent of each other. A snapshot release is currently available in Maven Central.
<pre lang="xml"> <dependencies> <dependency> <groupId>com.eclipsesource.j2v8</groupId> <artifactId>j2v8_win32_x86</artifactId> <version>3.0.0-SNAPSHOT</version> <scope>compile</scope> </dependency> </dependencies> </pre>
In short, it means you can now do this (although don’t forget to release the runtime when you’re done):
<pre lang="java"> new Thread(() -> V8.createV8Runtime().executeScript("...")).start(); </pre>
To test this, we created a merge sort that used separated V8Runtimes at each sort step. At each step, the list would be divided in half and two new V8Runtimes were created. Each V8Runtime executed the merge sort algorithm in parallel, and the results were merged together. Just for fun, we ran 10 parallel merge sorts.
We managed to remove all shared data structures between different instances of the V8Runtime, allowing the entire system to run without locks. This greatly improved performance.
For more information on J2V8 and for future updates, follow me on Twitter.