Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using SharedArrayBuffer for Shared Memory in Node.js
📖 Scenario: You are building a Node.js application that needs to share a simple counter between two worker threads. This counter will be stored in shared memory so both threads can read and update it safely.
🎯 Goal: Create a shared memory buffer using SharedArrayBuffer and use it to share a counter between threads. You will set up the shared buffer, configure a typed array to access it, update the counter, and finally export the shared buffer for use in worker threads.
📋 What You'll Learn
Create a SharedArrayBuffer of 4 bytes
Create an Int32Array view on the shared buffer
Initialize the counter to zero
Export the shared buffer for use in other modules
💡 Why This Matters
🌍 Real World
SharedArrayBuffer is used in Node.js applications to share memory between worker threads efficiently. This is useful for performance-critical tasks like parallel processing or real-time data sharing.
💼 Career
Understanding shared memory and worker threads is important for backend developers working on scalable Node.js applications that require concurrency and performance optimization.
Progress0 / 4 steps
1
Create a SharedArrayBuffer
Create a variable called sharedBuffer and assign it a new SharedArrayBuffer with a size of 4 bytes.
Node.js
Hint
Use new SharedArrayBuffer(4) to create a buffer that can hold one 32-bit integer.
2
Create an Int32Array view on the shared buffer
Create a variable called sharedArray and assign it a new Int32Array that uses sharedBuffer as its buffer.
Node.js
Hint
Use new Int32Array(sharedBuffer) to create a typed array view on the shared buffer.
3
Initialize the counter to zero
Set the first element of sharedArray to 0 to initialize the shared counter.
Node.js
Hint
Assign 0 to sharedArray[0] to start the counter at zero.
4
Export the shared buffer
Export the sharedBuffer variable using module.exports so it can be imported by worker threads.
Node.js
Hint
Use module.exports = { sharedBuffer } to share the buffer with other files.
Practice
(1/5)
1. What is the main purpose of SharedArrayBuffer in Node.js?
easy
A. To create a memory area that multiple threads can access simultaneously
B. To store large strings efficiently
C. To replace regular arrays with faster versions
D. To handle file system operations asynchronously
Solution
Step 1: Understand Shared Memory Concept
SharedArrayBuffer is designed to create a block of memory that can be shared between multiple threads or workers.
Step 2: Compare with Other Options
Options B, C, and D describe unrelated features: string storage, array speed, and file system operations, which are not the purpose of SharedArrayBuffer.
Final Answer:
To create a memory area that multiple threads can access simultaneously -> Option A
Quick Check:
Shared memory = multiple threads access [OK]
Hint: SharedArrayBuffer is about sharing memory across threads [OK]
Common Mistakes:
Thinking it stores strings or files
Confusing with normal arrays
Assuming it handles async file tasks
2. Which of the following is the correct way to create a SharedArrayBuffer of 1024 bytes in Node.js?
easy
A. const sab = SharedArrayBuffer(1024);
B. const sab = SharedArrayBuffer.new(1024);
C. const sab = new SharedArrayBuffer();
D. const sab = new SharedArrayBuffer(1024);
Solution
Step 1: Check the correct constructor usage
The SharedArrayBuffer must be created with the new keyword and a size in bytes as argument.
Step 2: Validate each option
const sab = new SharedArrayBuffer(1024); uses new SharedArrayBuffer(1024), which is correct. const sab = SharedArrayBuffer(1024); misses new. const sab = new SharedArrayBuffer(); misses size argument. const sab = SharedArrayBuffer.new(1024); uses invalid syntax.
Final Answer:
const sab = new SharedArrayBuffer(1024); -> Option D
Quick Check:
Use new with size in bytes [OK]
Hint: Always use 'new' with SharedArrayBuffer and specify size [OK]
Common Mistakes:
Omitting 'new' keyword
Not providing size argument
Using incorrect constructor syntax
3. Given the code below, what will be the output?
const sab = new SharedArrayBuffer(4);
const int32 = new Int32Array(sab);
int32[0] = 10;
Atomics.add(int32, 0, 5);
console.log(int32[0]);
medium
A. 10
B. 5
C. 15
D. NaN
Solution
Step 1: Understand initial value and Atomics.add
The int32[0] is set to 10. Then Atomics.add adds 5 to this value atomically.
Step 2: Calculate the new value
10 + 5 = 15, so int32[0] becomes 15.
Final Answer:
15 -> Option C
Quick Check:
Atomics.add adds value safely = 15 [OK]
Hint: Atomics.add adds value and returns old value, array updates [OK]
Common Mistakes:
Expecting Atomics.add to return new value
Ignoring atomic operation effect
Confusing initial and updated values
4. What is wrong with the following code snippet?
const sab = new SharedArrayBuffer(8);
const uint8 = new Uint8Array(sab);
uint8[0] = 255;
Atomics.store(uint8, 0, 256);
console.log(uint8[0]);
medium
A. Atomics.store cannot be used with Uint8Array
B. 256 is out of range for Uint8Array element
C. SharedArrayBuffer size is too small
D. Uint8Array cannot be created from SharedArrayBuffer
Solution
Step 1: Check Uint8Array element range
Uint8Array elements can only hold values from 0 to 255. The value 256 is out of this range.
Step 2: Understand effect of storing 256
Storing 256 wraps around to 0 because 256 mod 256 = 0, so uint8[0] becomes 0, not 256.
Final Answer:
256 is out of range for Uint8Array element -> Option B
Quick Check:
Uint8 max value 255, 256 wraps to 0 [OK]
Hint: Uint8Array values must be 0-255; higher values wrap [OK]
Common Mistakes:
Assuming Atomics.store rejects Uint8Array
Ignoring value wrapping behavior
Thinking SharedArrayBuffer size is insufficient
5. You want to safely increment a shared counter in a Node.js worker thread using SharedArrayBuffer. Which code snippet correctly increments the counter without race conditions?
// Shared buffer and typed array
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
counter[0] = 0;
// Increment function
function increment() {
// Which line correctly increments?
}
hard
A. Atomics.add(counter, 0, 1);
B. counter[0] = counter[0] + 1;
C. counter[0] += 1;
D. counter[0]++;
Solution
Step 1: Understand race conditions in shared memory
Directly modifying counter[0] with normal operators can cause race conditions when multiple threads run concurrently.
Step 2: Use atomic operations for safe increments
Atomics.add(counter, 0, 1) safely increments the value at index 0 without conflicts.
Final Answer:
Atomics.add(counter, 0, 1); -> Option A
Quick Check:
Use Atomics for safe shared memory updates [OK]
Hint: Always use Atomics methods to update shared memory safely [OK]