{"id":1582,"date":"2018-05-03T22:08:54","date_gmt":"2018-05-03T22:08:54","guid":{"rendered":"http:\/\/capture.ccio.us\/?p=1582"},"modified":"2018-05-03T22:08:54","modified_gmt":"2018-05-03T22:08:54","slug":"multi-threaded-javascripting-using-nashorn-javascript-engine","status":"publish","type":"post","link":"https:\/\/capture.club\/portal\/2018\/05\/03\/multi-threaded-javascripting-using-nashorn-javascript-engine\/","title":{"rendered":"Multi-threaded JavaScripting Using the Nashorn JavaScript Engine"},"content":{"rendered":"<body><p>I have been writing JavaScript for enterprise applications for more than 20 years. From that statement, it\u2019s easy to discern that I\u2019ve been a JavaScript advocate for a long, long time. JavaScript is a truly unique language, sporting qualities <a href=\"http:\/\/www.crockford.com\/javascript\/javascript.html\">found in both procedural and functional languages<\/a>. Despite this, there has always been one glaring missing feature: the concept of multi-threading. Over the years, I\u2019ve come up with a variety of workarounds to emulate threading, yet it was not until Java switched from the Rhino to the Nashorn compiler that truly multi-threaded processing in JavaScript became possible.<br>\nTo that end, I\u2019ve provided a couple examples of how to instantiate a thread in a JavaScript stage. \u00a0You might want to use this for things like <a href=\"https:\/\/lucidworks.com\/2017\/02\/03\/streaming-in-a-javascript-stage\/\">streaming queries<\/a>, background logging or processing, and so on.<\/p>\n<h3>The Code:<\/h3>\n<div>\n<blockquote>\n<pre>\n function (doc) {\n                logger.info(\"BEGIN THREAD TEST ****** \");\n                try {\n                    \/\/ EXAMPLE 1 - Thread in Extended Runnable\n                    var Runnable = Java.type('java.lang.Runnable');\n                    var Printer = Java.extend(Runnable, {\n                        run: function () {\n                            logger.info('printed from a separate thread');\n                        }\n                    });\n                    var Thread = Java.type('java.lang.Thread');\n                    new Thread(new Printer()).start();\n                    \/\/ EXAMPLE 2 - Thread Only\n                    new Thread(function () {\n                        logger.info('printed from another thread');\n                    }).start();\n                } catch (err) {\n                    logger.error(err);\n                }\n                return doc;\n            }\n<\/pre>\n<\/blockquote>\n<\/div>\n<h3>Breaking it down<\/h3>\n<p>So what is going on here? \u00a0The above code actually starts two separate threads: one running in the context of an extended Runnable, and the other is a standalone thread. \u00a0The snippets are relative short, so I don\u2019t think we need to break out snippets. \u00a0The long and the short of it is that you declare a mult-threading enabled class (anything that implements\u00a0<a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/Runnable.html\">Runnable<\/a>), pass a function to it as an argument, and start it.<br>\nNow, I realize that I\u2019m letting my inner geek show here, but I really think this is wildly cool. \u00a0You can now run <em>functional<\/em> logic within the scope of a <em>procedural<\/em> object. \u00a0It really doesn\u2019t get much cooler than that!<br>\nAll that said, there are some serious caveats you need to consider:<\/p>\n<ol>\n<li>If you start your own thread, you\u2019re responsible for stopping it. \u00a0Make sure you factor this responsibility into your code.<\/li>\n<li>The numbers of threads allowed in the JVM is finite. \u00a0You want to start (and stop) your threads explicitly, gracefully, and use them sparingly. \u00a0Keep in mind that a custom process spinning up a large number of threads could potentially conflict with other processes in the pipeline.<\/li>\n<li>Don\u2019t use a thread in your pipeline unless it is absolutely necessary.<\/li>\n<\/ol>\n<p>\u00a0<br>\nSo to summarize: Threading is now possible in JavaScript, and it\u2019s pretty darn cool, but use it wisely.<\/p>\n<\/body>","protected":false},"excerpt":{"rendered":"<p>I have been writing JavaScript for enterprise applications for more than 20 years. From that statement, it\u2019s easy to discern that I\u2019ve been a JavaScript advocate for a long, long time. JavaScript is a truly unique language, sporting qualities found in both procedural and functional languages. Despite this, there has always been one glaring missing [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[],"tags":[],"class_list":["post-1582","post","type-post","status-publish","format-standard","hentry"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/posts\/1582","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/comments?post=1582"}],"version-history":[{"count":0,"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/posts\/1582\/revisions"}],"wp:attachment":[{"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/media?parent=1582"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/categories?post=1582"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/capture.club\/portal\/wp-json\/wp\/v2\/tags?post=1582"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}