Sunday, September 27, 2015

Java8-Nashorn

https://github.com/maheshrajannan/java8Nashorn2

Excitement aside. Please note down the below,

1. Javascript context has a single threaded event loop, Task Que and , Execution context.
2. Callback functions are put in to Java Scripts task queue by the Calling Execution context. In case of browser, it is the browser API.
3. All window (in browser) functions are not available in nashhorn.
4. As the calling context of Javascript is nashorn, there is not asynchronous call back execution after java completes.

Feel free to import this as a maven project and run the junit tests. It has the java8 nashorn concepts tested and explored in depth.

       

	/**
	 * Test method for
	 * {@link java8Group.java8Artifact.js.java.AsynchronousJs.
         * java.AsynchronousJsTest#main(java.lang.String[])}
	 * .
	 * 
	 * INFO: "console.log("I just timed out!");" never gets called from nashorn
	 * javascript engine because the engine exits as soon as it gets evaluated.
	 * In short, the execution context of nashorn javascript engine, is short
	 * lived just like your java main thread. It therefore behaves differently
	 * from browser(web) context, because browser context is long lived than the
	 * nashorn(java) context. So java script is a single threaded event
	 * loop.Browser, plugs in a callback function, to the task queue and
	 * javascript's event loop executes it. This("console.log("I just timed
	 * out!");") does NOT happen from nashorn context.
	 * 
	 * @throws ScriptException
	 * @throws FileNotFoundException
	 * @throws NoSuchMethodException
	 */
	@Test
	public void testAsyncCall() throws FileNotFoundException, ScriptException,
			NoSuchMethodException {
		nashornInterface.evaluateJsFile(
				"src/main/java/java8Group/java8Artifact/js/asynchronous.js");
		String result = (String) nashornInterface.getInvocable()
				.invokeFunction("asynccall");
		System.out.println("Result of async call : " + result);
		Assert.assertEquals("Result is unexpected ", result, "SUCCESS");
	}


       
 

No comments:

Post a Comment