NodeJS is NOT automatically thread-safe
# Node Thread-Safety Example
A common explanation of node thread-safety is often that since Node
is "single threaded", all threads are safe.
A more qualified answer may state "except when it comes to asynchronous tasks", or "when using globals".
The problem is that ignoring the asynchronous nature of Node during I/O operations or longer running tasks can lead to unintended consequences. For example, suppose you have some code that maintains a single OIDC token that is being used to call an API on another host. You should maintain a single instance of that token, until it expires (or near to it to accommodate for clock skew). Two requests come in and it is determined that the token needs to be refreshed. Request1 makes a token refresh API call, Request2, unaware of the token refresh being performed by Request1, also issues a token refresh call. Now multiply that by however many requests come in while waiting on the refresh API call to complete. Many people will say, all the tokens that are retrieved will work, no harm no foul, but nothing is free. In many cases, such token refresh calls will be throttled or limited.
If it takes time T to retrieve a refreshed OIDC token. All requests that are performing this refresh will now have to wait time T before they can continue. When Request2 comes in .5T after Request1, if Request2 waited for Request1 to complete the refresh of the shared token, Request2 would only have to wait .5T for the token to be refreshed, and the wait time only improves for subsequent requests that need to wait for the token to be refreshed.
Some general rules of thumb when working with module globals or singleton class members that are shared by requests:
1. Set once during construction or global module initialization. If setting is asynchronous, and done one time only, set the global/member to a Promise or Promise'T.
2. If a global/member value needs to be updated, use some locking/synchronizing mechanism, such as a mutex, to prevent multiple updates. If an update condition is true, after entering the synchronized code block, check again if the value needs to be updated. The value may already have been updated while waiting on a lock to be released.
References:
https://blog.logrocket.com/node-js-multithreading-worker-threads-why-they-matter/
Example code:
https://github.com/rcollette/node-thread-safety
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «NodeJS is NOT automatically thread-safe», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.