user3828771
user3828771

Reputation: 1663

race condition issue in node?

People says that single-threaded languages like Javascript can not got that issue. However, nodejs provides cluster to fork multiple workers. Is this gonna cause race condition problem?

And also, I have an example that causes my confusion sometimes:

ALLSESSIONS = {};
//session id saved in cookie
ALLSESSIONS[sessionid] = 'somevalue';

var SESSION = ALLSESSIONS[sessionid];
... do stuff for sometimes
console.log(SESSION);

I'm afraid that when another request reaches node while the current request is still running, it may overwrite the SESSION variable with its own session id, then the result of current request is undetermined.

Is this gonna happen in node?

Upvotes: 1

Views: 505

Answers (1)

Hamilton Lucas
Hamilton Lucas

Reputation: 419

When another request reaches node while the current request is still running, it will not overwrite the session variable with its own.

Cluster allows you to have multiple workers, and these workers will all be separate from each other. This means that if your ALLSESSIONS variable is scoped to a single worker, then it will actually only contain session information for the given worker. You would need your ALLSESSIONS variable to be scoped at the application (pre-fork) level in order to share it across workers.

However, keeping session information in memory is probably not a good idea to begin with! If your worker or application threads crash, then you've lost your session data. It may be better to use a persistent store of some sort.

In general, race conditions are likely to occur if you have a globally scoped variable being written to and read from multiple request threads.

Upvotes: 1

Related Questions