1

I am using an array to store a list of connected clients.

Whenever I wish to iterate through the client list I do: clients.forEach(...).

My question is, is this thread safe, as what if a client disconnects (and is therefore removed from clients) during the a clients.forEach(...) statement?

1 Answer 1

2

Short answer is yes.

forEach is a synchronous process, meaning that the array would not be modified until the process has finished executing the forEach loop on the array.

This is my understanding from reading: Are nodejs data-structures thread-safe by design?

Sign up to request clarification or add additional context in comments.

5 Comments

While the short answer is true, the reasoning is wrong. .forEach is synchronous and thus no other code is running at the same time.
You should also mention that Node.js is single threaded and therefore threading issues can usually be ignored.
what if you change the array as part of the fn you are passing to forEach ?x.forEach(function(a){console.log(a);x.push(a)}); Where x is the initial array in the scope.
the statement "the array would not be modified" is not entirely true. Array can still be modified as part of the fn passed to forEach.
You are correct that an array can be modified as part of the function passed to forEach, but in this specific case, the array would not be modified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.