I have been writing JavaScript for enterprise applications for more than 20 years. From that statement, it’s easy to discern that I’ve 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 feature: the concept of multi-threading. Over the years, I’ve 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.

To that end, I’ve provided a couple examples of how to instantiate a thread in a JavaScript stage.  You might want to use this for things like streaming queries, background logging or processing, and so on.

The Code:

 
 function (doc) {
                logger.info("BEGIN THREAD TEST ****** ");
                try {
                    // EXAMPLE 1 - Thread in Extended Runnable
                    var Runnable = Java.type('java.lang.Runnable');
                    var Printer = Java.extend(Runnable, {
                        run: function () {
                            logger.info('printed from a separate thread');
                        }
                    });

                    var Thread = Java.type('java.lang.Thread');
                    new Thread(new Printer()).start();
                     
                    // EXAMPLE 2 - Thread Only
                    new Thread(function () {
                        logger.info('printed from another thread');
                    }).start();
                } catch (err) {
                    logger.error(err);
                }
                return doc;
            }

Breaking it down

So what is going on here?  The above code actually starts two separate threads: one running in the context of an extended Runnable, and the other is a standalone thread.  The snippets are relative short, so I don’t think we need to break out snippets.  The long and the short of it is that you declare a mult-threading enabled class (anything that implements Runnable), pass a function to it as an argument, and start it.

Now, I realize that I’m letting my inner geek show here, but I really think this is wildly cool.  You can now run functional logic within the scope of a procedural object.  It really doesn’t get much cooler than that!

All that said, there are some serious caveats you need to consider:

  1. If you start your own thread, you’re responsible for stopping it.  Make sure you factor this responsibility into your code.
  2. The numbers of threads allowed in the JVM is finite.  You want to start (and stop) your threads explicitly, gracefully, and use them sparingly.  Keep in mind that a custom process spinning up a large number of threads could potentially conflict with other processes in the pipeline.
  3. Don’t use a thread in your pipeline unless it is absolutely necessary.

 

So to summarize: Threading is now possible in JavaScript, and it’s pretty darn cool, but use it wisely.

About Kevin Cowan

Read more from this author

Best of the Month. Straight to Your Inbox!
Dive into the best content with our monthly Roundup Newsletter! Each month, we handpick the top stories, insights, and updates to keep you in the know.