Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correctly or fail, without experiencing lost updates or double processing.

While I have extensive experience testing similar scenarios in Java due to its abundance of concurrency primitives like semaphores and barriers, I am struggling to translate this knowledge into TypeScript.

In Java, for instance, I would initiate 2 threads using a CyclicBarrier with 2 parties. These threads would reach the barrier, wait for each other, then continue execution, allowing me to validate the code's functionality effectively. If parallel execution could not be guaranteed, I would repeat the test multiple times or use more threads to increase chances of parallelism.

Unfortunately, I have not come across any similar concurrency primitives in JS to replicate this process. The closest workaround I found was busy waiting on a shared value or utilizing worker threads as suggested by some blogs.

If anyone has suggestions on how to approach this challenge in TypeScript, I would greatly appreciate it! This topic poses several difficulties, so links to relevant blogs, articles, and books are welcome!

Answer №1

It is crucial to note that unlike Java or other programming languages, JavaScript (in this case TypeScript) runs on a single thread. This means that only one line of TS/JS code can execute at a time. Although there are workarounds like WebWorkers, for the purpose of this discussion, let's assume they are not being utilized.

If your library will be used in an environment where multiple instances of your application are running concurrently, you will have truly parallel systems. For now, let's focus on the scenario where this is not the case.

Evaluating concurrency within a single node process

In this context, understanding how JS handles events via the event loop is key. Philip Roberts has an insightful talk on this topic from JSConf.

With a single node process and assuming the use of "async" functions, Promises are executed concurrently. However, the actual switching between asynchronous tasks occurs when performing operations like IO, web requests, etc.

A simple way to test your library under these conditions could be:

function test() {
    Promise.all([
        doSomething(),
        doSomething(),
    ]);
}

Evaluating concurrency in a multi-process environment

If your application is deployed across multiple machines simultaneously, testing becomes more complex. Directly simulating this scenario is challenging as initiating tests that call functions simultaneously requires starting multiple processes.

I would caution against attempting such tests, especially if the tasks you are evaluating are quick, as it may lead to unreliable results. Introducing an artificial delay by extending critical sections to take several seconds and calling both instances sequentially might provide better insights. Using Promise.all() here can help maximize concurrency effects. Ensure to account for potential misbehaviors during execution.

As for setting up and executing tests involving two processes, consider creating a web worker to establish a new V8 execution context in Node.js, or leverage a simple HTTP server for communication.

Considering alternative solutions

Given the inherent single-threaded nature of JavaScript, achieving true parallelism beyond Promise.all can be challenging. A possible workaround could involve writing a small script in another language to assess this behavior. While languages like Rust offer robust concurrency primitives, interoperability with JavaScript may present some challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to trigger an error, the unit test will fail to pass

I am relatively new to Mocha, Chai, and Unit Testing. I'm currently attempting to create a basic test to verify the presence of Authorization headers in the request that passes through my middleware function. Despite trying various approaches such as ...

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

Error: The AJAX request encountered an unexpected token in the JSON response

I am working with the following code snippet: $.ajax({ dataType: 'text', url: '/_/js/answers.json', type: "GET", success: function (data) { alert(data); ...

Show information from a JSON file in a tooltip on a Highcharts' pie chart

I have a pie chart that shows two percentages. I am looking to update the tooltip content to display information from my JSON data. Here is an example of how my JSON data looks: {"object1":{"percentage": 0.7, "numberOfObject": 167}, "object2":{"percentage ...

Guide to asynchronously loading images with Bearer Authorization in Angular 2 using NPM

I am in search of a recent solution that utilizes Angular2 for my image list. In the template, I have the following: <div *ngFor="let myImg of myImages"> <img src="{{myImg}}" /> </div> The images are stored as an array w ...

Encountering challenges with Object-Oriented Programming combined with Typescript: Are you experiencing a

Currently, I'm in the process of building a comprehensive authentication application using the MERN stack entirely in TypeScript. However, I am encountering some issues (specifically type errors) with my userController file. Here is my routes file: i ...

Setting up a Progressive Web App installation feature with a built-in delay from a

I have integrated a v-dialog component that shows up when my webapp loads and is utilized for installing the PWA: <template> <div> <v-dialog v-model="popupAndroid" max-width="80%" ...

What is the process for registering a click using a class in jQuery and retrieving the ID of the clicked element?

Currently, I am working on developing a webpage where I need to use jQuery to register a click using the items class and then extract the ID of that particular object. For example: HTML: <div class="exampleclass" id="exampleid1"></div> <d ...

Error: This property is not available on either 'false' or 'HTMLAudioElement' types

When working with React (Next.js) using hooks and typescript, I encountered an issue while trying to create a reference to an Audio element. The error message I received was: Property 'duration' does not exist on type 'false | HTMLAudioEleme ...

Monitoring data updates within an Angular directive

Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable? Currently, I am loading a basic dataset from a JSON file usin ...

"Encountering a bug with Angular-bootstrap pagination displaying an undefined function

Attempting to implement angular-bootstrap pagination footer Encountering an error TypeError: undefined is not a function at Object.fn (http://localhost:3000/lib/angular-bootstrap/ui-bootstrap-tpls.js:2265:5) at Scope.$get.Scope.$digest (http://l ...

Is sending a stream to a variable the best option, or could there be another solution

Is there a way to pipe stream data to a variable? The writable stream examples mentioned in this documentation include: HTTP requests on the client side HTTP responses on the server side Zlib streams Crypto streams TCP sockets Child process stdin Process ...

TypeORM issue - UnsupportedDataTypeError

Here is the entity file I'm working with, user.ts: @Entity('users') export class User { @PrimaryGeneratedColumn() id: number | undefined; @Column({ type: 'string', name: 'username', nullable: true }) username: s ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

What are the best practices for integrating RxJS into Angular 2 projects?

How can I write code like this in Angular 2? var closeButton1 = document.querySelector('.close1'); var close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click'); I have attempted various methods to incorporate this into an An ...

Exploring the connected component feature in React/Redux

While testing the connected component of my React/Redux app, I encountered an error. The test case that caused the error is: App component › shows account info and debits and credits` Invariant Violation: Could not find "store" in either the context or ...

Dominating React Components with Unique CSS Styles

Currently, I have developed a NavBar component. I've implemented some JavaScript code that changes the navbar's background color once it reaches 50px. However, I am facing an issue in applying this scroll effect to only one specific file and not ...

Issues encountered when executing unit tests using karma

I encountered these issues in the logs. Seeking advice on how to proceed. Thank you. I've attempted uninstalling and reinstalling phantomjs, clearing out my node modules and bower component directories. Everything was functioning as expected before, a ...